遗憾的是我无法使用标记值来获取切换检测到更改行...主要是我需要知道特定的切换更改了行文本"早上好"从我的数组中搜索一些东西。所以任何人都可以帮助我,我怎样才能在 switchChanged 方法中获得cell textLabel text
。谢谢
代码示例:
func switchChanged(_ sender : UISwitch!){
print("table row switch Changed \(sender.tag)")
print("The switch is \(sender.isOn ? "ON" : "OFF")")
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "yourcellIdentifire", for: indexPath) as! YourCellClass
cell.textLabel?.text = "bad morning"
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
}
答案 0 :(得分:1)
您可以向YourCellClass
添加委托。当切换switchView时,调用类似于
class YourCellClass: UITableViewCell {
weak var delegate:YourCellClassDelegate?
var switchView: UISwitchView
init() {
...other stuff...
switchView.addTarget(self, action: #selector(self.switchChanged(_:)), for: .valueChanged)
...other stuff...
}
func switchChanged(_ sender : UISwitch!){
if let delegate = delegate {
delegate.cellDidToggleSwitch(self, isOn: sender.isOn)
}
}
}
protocol YourCellClassDelegate {
func cellDidToggleSwitch(_ cell: YourCellClass, isOn: Bool)
}
然后在ViewController中使用TableView
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 { // specific row showing switch
var cell = tableView.dequeueReusableCell(withIdentifier: "yourcellIdentifire", for: indexPath) as! YourCellClass
cell.textLabel?.text = "bad morning"
cell.delegate = self
return cell
}
return UITableViewCell()
}
func cellDidToggleSwitch(_ cell: YourCellClass, isOn: Bool) {
//here's your cell
}
答案 1 :(得分:0)
您是否尝试过传递给函数switchChanged IndexPath?我的意思是两个参数,发送者和indexPath。