在 Swift 中的 UITableView 单元格中添加开关
Add switch in UITableView cell in Swift
如何以编程方式将 UISwitch
嵌入到 Swift 的 tableView 单元格中?
我就是这样做的
let shareLocationSwitch = UISwitch()
cell.accessoryView = shareLocationSwitch
这是在 UITableView
单元格上嵌入 UISwitch
的方法。
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 call 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
UITableViewCell
awakeFromNib
方法而不是 table 查看 cellForRowAt
方法。将可重用 cell
出队时将其投射到您的 CustomCell Here is sample from @LeoDabus
如果您使用 3 个元素更新数组并使用 self.tableView.reloadData() 刷新 table(例如 2 秒后),您可以看到使用 Xcode13 时开关值将被交换并且该示例不起作用。当 Xcode 发布到 13 时,我的应用程序也有类似的问题。试试这个:https://drive.google.com/file/d/1_1HuI_JFIYusNmsdyekGBWXsGznneiQ7/view?usp=sharing
如何以编程方式将 UISwitch
嵌入到 Swift 的 tableView 单元格中?
我就是这样做的
let shareLocationSwitch = UISwitch()
cell.accessoryView = shareLocationSwitch
这是在 UITableView
单元格上嵌入 UISwitch
的方法。
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 call 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
UITableViewCell
awakeFromNib
方法而不是 table 查看 cellForRowAt
方法。将可重用 cell
出队时将其投射到您的 CustomCell Here is sample from @LeoDabus
如果您使用 3 个元素更新数组并使用 self.tableView.reloadData() 刷新 table(例如 2 秒后),您可以看到使用 Xcode13 时开关值将被交换并且该示例不起作用。当 Xcode 发布到 13 时,我的应用程序也有类似的问题。试试这个:https://drive.google.com/file/d/1_1HuI_JFIYusNmsdyekGBWXsGznneiQ7/view?usp=sharing