将您的复选框与视图控制器相连,如下所示:
class ViewController: UIViewController {
@IBOutlet weak var checkBox1: UISwitch!
@IBOutlet weak var checkBox2: UISwitch!
}
Run Code Online (Sandbox Code Playgroud)
然后将第一个复选框的IBAction添加到视图控制器,并使用if else切换第二个复选框,如下所示:
class ViewController: UIViewController {
@IBOutlet weak var checkBox1: UISwitch!
@IBOutlet weak var checkBox2: UISwitch!
@IBAction func checkBox1Pressed(_ sender: UISwitch) {
// using if else
if checkBox1.isOn {
checkBox2.setOn(true, animated: true)
} else {
checkBox2.setOn(false, animated: true)
}
}
}
Run Code Online (Sandbox Code Playgroud)
或使用三元运算符,例如:
class ViewController: UIViewController {
@IBOutlet weak var checkBox1: UISwitch!
@IBOutlet weak var checkBox2: UISwitch!
@IBAction func checkBox1Pressed(_ sender: UISwitch) {
// or using ternary operator
checkBox1.isOn ? checkBox2.setOn(true, animated: true) : checkBox2.setOn(false, animated: true)
}
}
Run Code Online (Sandbox Code Playgroud)
结果:
如果您不使用UISwitch,请使用当前代码更新您的问题
由于OP的评论而进行了更新:
将您的复选框与视图控制器相连,如下所示:
class ViewController: NSViewController {
@IBOutlet weak var checkBox1: NSButton!
@IBOutlet weak var checkBox2: NSButton!
}
Run Code Online (Sandbox Code Playgroud)
然后将第一个复选框的IBAction添加到视图控制器,并使用if else切换第二个复选框,如下所示:
class ViewController: NSViewController {
@IBOutlet weak var checkBox1: NSButton!
@IBOutlet weak var checkBox2: NSButton!
@IBAction func checkBox1Pressed(_ sender: NSButton) {
// Note: state checked == 1, state unchecked == 0
// if checkBox1 is checked
if checkBox1.state == 1 {
// also set checkBox2 on checked state
checkBox2.state = 1
} else {
// uncheck checkBox2
checkBox2.state = 0
}
}
}
Run Code Online (Sandbox Code Playgroud)
或使用三元运算符,例如:
class ViewController: NSViewController {
@IBOutlet weak var checkBox1: NSButton!
@IBOutlet weak var checkBox2: NSButton!
@IBAction func checkBox1Pressed(_ sender: NSButton) {
// Note: state checked == 1, state unchecked == 0
// or using ternary operator
checkBox1.state == 1 ? (checkBox2.state = 1) : (checkBox2.state = 0)
}
}
Run Code Online (Sandbox Code Playgroud)
结果:
| 归档时间: |
|
| 查看次数: |
1569 次 |
| 最近记录: |