如何在自定义单元格中切换开关切换函数 - TableViewCell Swift

kur*_*odu 1 uitableview ios swift

我在自定义单元格中有一个切换按钮,插入到tableView中.如何在切换按钮切换时更新tableview?

下面是我插入包含toggleSwitch的自定义tableViewCell的函数

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
  let cell = Bundle.main.loadNibNamed("AvailabilityTableViewCell", owner: self, options: nil)?.first as! AvailabilityTableViewCell
            
  // Configure the cell...
  cell.availabilityLabel.text = "Available"
  switchIsOn = cell.availabilitySwitch.isOn
  return cell
            
 }
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

Tho*_*ich 5

UISwitch是一个子类UIControl,允许您在其上设置目标/操作:

在您的实现中实现以下功能UIViewController:

func toggled(sender: UISwitch) {
   // React to switch being toggled here
}
Run Code Online (Sandbox Code Playgroud)

在你的cellForRowAt:现在你可以将目标/动作添加到单元格UISwitch:

cell.availabilitySwitch.addTarget(self, action: #selector(toggled:), for: .valueChanged)
Run Code Online (Sandbox Code Playgroud)