Swift - 选中时切换UIButton标题

时间:2017-01-20 22:51:58

标签: ios swift uibutton uicontrol uicontrolstate

我正在寻找一个可以用作复选框的按钮,并使用户能够以开/关方式切换复选框(未勾选/勾选)。目前我使用属性检查器设置我的按钮,包括“标题”为“X”,“文本颜色”为红色。

一旦加载,按钮就会显示一个红色的“X”,一旦点击它就会变成一个绿色的勾号。

我的问题是...... 如何启用按钮再次点击以恢复为红色X(它的原始状态),每当点击时都会继续循环?

    @IBAction func check2(_ sender: UIButton) {
     sender.setTitle("✓", for: .normal)
    sender.setTitleColor(UIColor.green, for: UIControlState.normal)
}

谢谢

2 个答案:

答案 0 :(得分:9)

使用变量跟踪状态并根据状态更新外观:

    class ViewController: UIViewController{
        @IBOutlet weak var button: UIButton!
        var isChecked = true

        @IBAction func check2(_ sender: UIButton) {
            isChecked = !isChecked
            if isChecked {
                sender.setTitle("✓", for: .normal)
                sender.setTitleColor(.green, for: .normal)
            } else {
                sender.setTitle("X", for: .normal)
                sender.setTitleColor(.red, for: .normal)
            }
        }
    }

答案 1 :(得分:6)

针对Swift 3进行了更新

lazy var toggleBT: UIButton = {

    let button = UIButton()
    button.frame = CGRect(x: 40, y: 100, width: 200, height: 40)
    button.backgroundColor = .orange
    button.isSelected = false   // optional(because by default sender.isSelected is false)
    button.setTitle("OFF", for: .normal)
    button.setTitleColor(.white, for: .normal)
    button.titleLabel?.font = .boldSystemFont(ofSize: 14)
    button.addTarget(self, action: #selector(handleToggleBT), for: .touchUpInside)
    return button
}()

func handleToggleBT(sender: UIButton) {

    sender.isSelected = !sender.isSelected

    if sender.isSelected {

        print(sender.isSelected)
        toggleBT.setTitle("ON", for: .normal)
    }

    else {

        print(sender.isSelected)
        toggleBT.setTitle("OFF", for: .normal)
    }
} // don't forget to add this button as a subView for eg. view.addSubview(toggleBT)

enter image description here