如何在 Swift 中以编程方式将 UISwitch
嵌入到 tableView 单元格中?
我就是这样做的
let shareLocationSwitch = UISwitch()
cell.accessoryView = shareLocationSwitch
最佳答案
您可以通过以下方式将 UISwitch
嵌入到 UITableView
单元格中。
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
}
这里是switch调用beck方法
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
并配置您的 accessoryView
inside UITableViewCell
awakeFromNib
方法而不是 TableView cellForRowAt
方法。将可重复使用的 cell
出队时将其转换为您的 CustomCell Here is sample from @LeoDabus
关于swift - 在 Swift 的 UITableView 单元格中添加开关,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47038673/