我正在寻找一个可以用作复选框的按钮,并使用户能够以开/关方式切换复选框(未勾选/勾选).目前我使用属性检查器设置我的按钮,包括"标题"为"X","文本颜色"为红色.
一旦加载,按钮就会出现一个红色的"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)