如何在Swift的tableView单元中以编程方式嵌入UISwitch? 我就是这样
How can I embed a UISwitch programmatically in a tableView cell in Swift? I'm doing it like that
let shareLocationSwitch = UISwitch() cell.accessoryView = shareLocationSwitch推荐答案
这是将UISwitch嵌入到UITableView单元格中的方法.
Here is way you can embed a UISwitch on a UITableView cell.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: "yourcellIdentifire", for: indexPath) as! YourCellClass //here is programatically switch make to the table view let switchView = UISwitch(frame: .zero) switchView.setOn(false, animated: true) switchView.tag = indexPath.row // for detect which row switch Changed switchView.addTarget(self, action: #selector(self.switchChanged(_:)), for: .valueChanged) cell.accessoryView = switchView return cell }这是切换呼叫贝克方法
func switchChanged(_ sender : UISwitch!){ print("table row switch Changed \(sender.tag)") print("The switch is \(sender.isOn ? "ON" : "OFF")") }
@LeoDabus Great! explanation.
注意:如果您的tableview可能有多个section,则应创建一个CustomCell子类UITableViewCell,并在UITableViewCell awakeFromNib方法内而不是表视图中配置accessoryView c10>方法.将可重用的cell出队时,将其投射到CustomCell 此处为示例来自@LeoDabus
Note: if your tableview may have more than one section then You should create a CustomCell subclassing UITableViewCell and configure your accessoryView inside UITableViewCell awakeFromNib method instead of table view cellForRowAt method. When dequeuing the reusable cell cast it to your CustomCell Here is sample from @LeoDabus
更多推荐
在Swift的UITableView单元格中添加开关
发布评论