代码之家  ›  专栏  ›  技术社区  ›  CoderJ13

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

  •  0
  • CoderJ13  · 技术社区  · 7 年前

    我有个按钮叫 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 回复  |  直到 7 年前
        1
  •  0
  •   Abdelahad Darwish    7 年前

    你可以做得比这更好,你必须在你的 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
                    }
                }
            }
        }