如何将这样的代码添加到您的 Bool 变量声明中:
var checkBoxFlag:Bool = false
{
didSet
{
if checkBoxFlag == true {myButton.state = NSOnState}
if checkBoxFlag == false {myButton.state = NSOffState}
myButton.display()
}
}
只要 checkBoxFlag 的值发生变化,就会执行 didSet 代码。
实际上,您可以使用它做更多事情。例如,如果您有一个名为 resetAnimation 的 Bool:
var resetAnimation:Bool = false
{
willSet(newResetAnimation)
{
("resetAnimation 即将由 (resetAnimation) 改为 \(newResetAnimation)")
}
设置
{
如果重置动画 == 真 {
println("resetAnimation 设置为 (resetAnimation)")
}别的{
println("resetAnimation 设置为 (resetAnimation)")
}
}
}
如果然后在你的代码中你写的其他地方:
resetAnimation = true
resetAnimation = false
resetAnimation = true
这将打印:
resetAnimation 即将由 false 变为 true
resetAnimation 设置为 true
resetAnimation 即将由 true 改为 false
resetAnimation 设置为 false
resetAnimation 即将由 false 改为 true
resetAnimation 设置为 true
编辑 - 测试:
所以这是测试场景。在应用程序中,我将此测试粘贴到我有一个带有控制器的状态窗口。该窗口有一个自定义进度指示器。我在状态窗口 .xib 文件中添加了一个无关的复选框,默认状态为 on。
在我声明的状态窗口控制器中
@IBOutlet var testCheckbox:NSButton!
并将 testCheckbox 连接到状态窗口中的无关复选框。
然后在状态窗口控制器中我声明了一个实例变量:
var checkBoxFlag:Bool = true
{
didSet
{
if checkBoxFlag == true {testCheckbox.state = NSOnState}
if checkBoxFlag == false {testCheckbox.state = NSOffState}
testCheckbox.display()
}
}
在用于更新自定义进度指示器的状态窗口控制器函数中,代码是(注意断点):
func updateStatusProgress(statusprogress:CGFloat)
{
println("In Update Status Before Change state = \(testCheckbox.state)");
if checkBoxFlag == true // breakpoint 1 here
{
checkBoxFlag = false
}else{
checkBoxFlag = true
}
println("In Update Status After Change state = \(testCheckbox.state)");
statusProgressIndicator.cgValue = statusprogress // Break point 2 here
statusProgressIndicator.display()
}
在打印的断点 1 处启动第一遍:
在 Update Status Before Change state = 1 并检查窗口时,复选框被选中。
在断点 2 处打印的应用程序:
在更改状态后更新状态 = 0 并检查窗口未选中复选框
进一步通过产生了相同的预期结果。
我在此处发布了我的代码,以防您发现此代码与您的代码之间关于其实现方式的一些差异。