UITableView复选框(按下另一个按钮时选择一个按钮)

时间:2018-05-27 11:34:04

标签: swift xcode uitableview checkbox uibutton

我有一个名为 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
}

1 个答案:

答案 0 :(得分:0)

你可以Handel工作比这更好,你必须在cellCellforRow仅管理状态

中执行此逻辑

任何方式你都可以这样做

 @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
                }
            }
        }
    }