Swift - 选择时切换 UIButton 标题

Swift - Toggle UIButton title when selected

我正在寻求实现一个可用作复选框并使用户能够以 on/off 方式 (unticked/ticked) 切换复选框的按钮。目前我已经使用属性检查器设置了我的按钮,包括 'Title' 作为 "X" 并且 'Text Color' 是红色的。

加载后按钮显示为红色 "X",点击后变为绿色对勾。

我的问题是...如何让按钮再次被点击以恢复到红色 X(它的原始状态),并在任何时候继续循环被窃听了?

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

谢谢

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

    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)
            }
        }
    }

更新 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)