我有一个名为 btnChk2 的按钮。我想在用户按 btnChk2 时选择按钮 btnChk 。以下是我的代码在我的代码中发生的情况是当 btnChk2 被按下时 btnChk2 被选中而不是 btnChk 。
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CheckBoxCell")
if let lbl = cell?.contentView.viewWithTag(1) as? UILabel {
lbl.text = "item-\(1)"
}
if let btnChk = cell?.contentView.viewWithTag(2) as? UIButton {
btnChk.addTarget(self, action: #selector(checkboxClicked(_ :)), for: .touchUpInside)
}
if let btnChk2 = cell?.contentView.viewWithTag(100) as? UIButton {
btnChk2.addTarget(self, action: #selector(checkboxClicked(_ :)), for: .touchUpInside)
}
return cell!
}
@objc func checkboxClicked(_ sender: UIButton) {
sender.isSelected = !sender.isSelected
}
答案 0 :(得分:0)
你可以Handel工作比这更好,你必须在cell
和CellforRow
仅管理状态
任何方式你都可以这样做
@objc func checkboxClicked(_ sender: UIButton) {
guard let cell = sender.superview?.superview as? UITableViewCell else {
return
}
if sender.tag == 2 {
if let btnChk2 = cell.contentView.viewWithTag(100) as? UIButton {
if btnChk2.isSelected == true {
btnChk2.isSelected = false
}else{
btnChk2.isSelected = true
}
}
sender.isSelected = false
}else if sender.tag == 100{
if let btnChk = cell.contentView.viewWithTag(2) as? UIButton {
if btnChk.isSelected == true {
btnChk.isSelected = false
}else{
btnChk.isSelected = true
}
}
}
}