在Swift中选中和取消选中复选框

时间:2017-04-03 07:33:01

标签: swift checkbox

如何在未找到swift 3 .selected属性中知道我的按钮是否被选中。

当我在Swift 3(Xcode 8.0)中找不到checkBtn.selected

 if let button = sender as? UIButton {
        if button.selected {
            // set selected
            button.selected = true
        } else {
            // set deselected
            button.selected = false
        }
    }

4 个答案:

答案 0 :(得分:2)

尝试以下代码

if let button = sender as? UIButton {
        if button.isSelected {
            // set selected
            button.isSelected = true
        } else {
            // set deselected
            button.isSelected = false
        }
    }

简而言之,试试这个

if let button = sender as? UIButton {
     button.isSelected = !button.isSelected
}

答案 1 :(得分:1)

在swift 3中,您将 isSelected 而不是选中。您的代码看起来很好,只需进行更改。

答案 2 :(得分:1)

if let button = sender as? UIButton {
    if button.isSelected {
        //for selected input            
    } else {
        //for not selected input 
    }
    button.isSelected = !button.isSelected //toggle the text box
}

答案 3 :(得分:0)

@IBOutlet weak var btnCheckBox: UIButton!
@IBAction func btnCheckBoxClick(_ sender: UIButton) {
        if btnCheckBox.isSelected {
            btnCheckBox.isSelected = false
            btnCheckBox.setImage(#imageLiteral(resourceName: "icon_checkbox_inactive"), for: .normal)
        }else {
            btnCheckBox.isSelected = true
            btnCheckBox.setImage(#imageLiteral(resourceName: "icon_checkbox_active"), for: .normal)
        }
    }

对我有用。