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

标签 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
}

最佳答案

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

关于swift - UITableView 复选框(按下另一个按钮时选择一个按钮),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50551701/

相关文章:

Swift 3、RxAlamofire 和映射到自定义对象

ios - 如何制作动画 spritekit 背景?

swift - 在 swift 中,为什么我不能实例化一个有初始化器的协议(protocol)?

ios - 如何检测设备是否为 iOS 8.3 中的 iPad?

Swift 编译器 2.1.1 永远卡在字典上

ios - 从解析列获取数组到 UITableView

ios - 与输入相比,谷歌地图显示不同的位置

ios - NSJSONSerialization 没有正确读取 UTF 8

objective-c - 在不同的 TableView 之间切换

iphone - 最接近 XCode、Windows 上的 Objective-C(不是 Hackintosh),也许是界面构建器