【问题标题】:Add switch in UITableView cell in Swift在 Swift 的 UITableView 单元格中添加开关
【发布时间】:2024-01-17 12:12:02
【问题描述】:

如何在 Swift 的 tableView 单元格中以编程方式嵌入 UISwitch? 我就是这样做的

let shareLocationSwitch = UISwitch()
cell.accessoryView = shareLocationSwitch

【问题讨论】:

  • 它是如此简单和容易,只需创建一个变量作为 UISwitch() 然后调用单元格 accesooryView ,您不需要做很多事情就可以到达那里,代码已经在问题中了。
  • 我只是编辑问题。感谢您的解决方案。
  • 为什么我的问题得到-2分,这真的很简单,在我找到一个好的解决方案后,我只是发送它并编辑问题,所以没有人会混淆。
  • 我现在有什么理由不关心它吗?

标签: swift uitableview swift3 cell uiswitch


【解决方案1】:

如果您使用 3 个元素更新数组并使用 self.tableView.reloadData() 刷新表(例如 2 秒后),您可以看到使用 Xcode13 的开关值将被交换,并且示例不起作用。当 Xcode 发布到 13 时,我的应用程序也遇到了类似的问题。试试这个:https://drive.google.com/file/d/1_1HuI_JFIYusNmsdyekGBWXsGznneiQ7/view?usp=sharing

【讨论】:

    【解决方案2】:

    这是您可以在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
          }
    

    这里是切换回叫方法

    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 方法而不是表视图@ 987654335@ 方法。将可重用的 cell 出列时,将其转换为您的 CustomCell Here is sample from @LeoDabus

    【讨论】:

    • 不是我的反对票,但可能是因为 tableview 可能有多个部分。您不应该为此使用标签属性
    • @NazmulHasan 您应该创建一个 CustomCell 子类 UITableViewCell 并在 UITableViewCell awakeFromNib 方法而不是 UITableViewController cellForRowAt 方法中配置您的附件视图。出列可重用单元格时,将其转换为您的 CustomCell
    • 我已经在示例中添加了部分,因此您可以在将来需要时用作参考dropbox.com/s/up4fp9plzyxtlii/…
    • 为什么不在 switchChanged 中使用 tableview.indexPath(for: sender.superview)
    最近更新 更多