在 Swift 中的 UITableView 单元格中添加开关 [英] Add switch in UITableView cell in Swift
问题描述
如何在 Swift 的 tableView 单元格中以编程方式嵌入 UISwitch
?我就是这样做的
让 shareLocationSwitch = UISwitch()cell.accessoryView = shareLocationSwitch
这是您可以在 UITableView
单元格上嵌入 UISwitch
的方法.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) ->UITableViewCell {var cell = tableView.dequeueReusableCell(withIdentifier: "yourcellIdentifire", for: indexPath) as!你的细胞类//这里以编程方式切换到表格视图让 switchView = UISwitch(frame: .zero)switchView.setOn(false, 动画: true)switchView.tag = indexPath.row//用于检测哪一行开关改变了switchView.addTarget(self, action: #selector(self.switchChanged(_:)), for: .valueChanged)cell.accessoryView = switchView返回单元格}
这里是 switch call beck 方法
func switchChanged(_ sender : UISwitch!){打印(表行开关已更改(sender.tag)")print("开关是(sender.isOn ? "ON" : "OFF")")}
<块引用>
@LeoDabus 太棒了!说明
.
注意:如果你的 tableview
可能有多个 section
那么你应该创建一个 CustomCell 子类 UITableViewCell
并配置你的 <UITableViewCell
awakeFromNib
方法中的 code>accessoryView 而不是 table view cellForRowAt
方法.将可重用 cell
出列时,将其投射到您的 CustomCell 这是@LeoDabus 的示例
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
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
}
here is switch call beck method
func switchChanged(_ sender : UISwitch!){
print("table row switch Changed (sender.tag)")
print("The switch is (sender.isOn ? "ON" : "OFF")")
}
@LeoDabus
Great! explanation
.
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 单元格中添加开关的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!