【问题标题】:UITableView Checkbox ( Select a button when another button is pressed )UITableView 复选框(按下另一个按钮时选择一个按钮)
【发布时间】:2018-05-27 11:34:04
【问题描述】:

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

【问题讨论】:

    标签: swift xcode uitableview checkbox uibutton


    【解决方案1】:

    你可以让 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
                    }
                }
            }
        }
    

    【讨论】:

    • 试过你的代码,但是当我按下 btnChk2 时,btnChk2 被选中,但我想要当我按下 btnChk2 来选中 btnChk。
    • 工作刚刚改变但是当我重新按下按钮时没有被取消选择
    • 你需要什么,当按2时选择一个,当按1时选择被取消
    • 当我添加 btnChk2.isSelected = !btnChk2.isSelected 时,按钮不再被选中。这是代码if sender.tag == 2 { if let btnChk2 = cell.contentView.viewWithTag(100) as? UIButton { btnChk2.isSelected = true btnChk2.isSelected = !btnChk2.isSelected } }else if sender.tag == 100{ if let btnChk = cell.contentView.viewWithTag(2) as? UIButton { btnChk.isSelected = true btnChk.isSelected = !btnChk.isSelected } }
    • 你需要什么,当按 2 时选择一个,当按 1 时选择被取消选择 – Abdelahad Darwish 4 分钟前编辑
    猜你喜欢
    • 2019-03-25
    • 2016-09-24
    • 2020-10-21
    • 2011-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-27
    相关资源
    最近更新 更多