问题描述
如何在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")")
}
注意:如果您的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单元格中添加开关的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!