我正在学习 KVC 和绑定(bind)。目前,我正在尝试将 NSTextField 绑定(bind)到计算属性 colorWallStr
。我已将 slider 的值绑定(bind)到相应的颜色变量,并将标签的值绑定(bind)到计算属性。
但是,当我移动幻灯片时,标签的内容并没有改变。
// Inside MainWindowController
dynamic var colorRed: CGFloat = 1.0
dynamic var colorGreen: CGFloat = 1.0
dynamic var colorBlue: CGFloat = 0.0
dynamic var colorWallStr: String {
get {
return "R: \(colorRed) G: \(colorGreen) B: \(colorBlue)"
}
}
当我将标签直接绑定(bind)到颜色变量时,它工作正常。
感谢@vadian 的回答。现在我可以使用属性的 didSet
来更新标签以触发更新标签方法(见下文)。
dynamic var colorBlue: CGFloat = 0.0 {
didSet {
updateLabel()
}
}
func updateLabel() {
colorWall = "R: \(colorRed) G: \(colorGreen) B: \(colorBlue)"
}
如果字符串插值中使用的属性不更新封闭的计算属性,那么为什么以下代码片段不起作用?
dynamic var colorWall: String {
get {
let red = colorRed
let green = colorGreen
let blue = colorBlue
return "R: \(red) G: \(green) B: \(blue)"
}
}
最佳答案
Key-Value Observering API 让您可以通过注册依赖键来处理这种情况。以下是文档介绍主题的方式:
There are many situations in which the value of one property depends on that of one or more other attributes in another object. If the value of one attribute changes, then the value of the derived property should also be flagged for change.
在这种情况下,colorWallString
的值取决于 三个颜色变量的值,因此您需要做的就是实现一个类方法来明确这一点:
// It's crucial that you get the signature of this method correct,
// otherwise it'll just be ignored.
class func keyPathsForValuesAffectingColorWallStr() -> Set<NSObject> {
return Set<NSObject>(arrayLiteral: "colorRed", "colorBlue", "colorGreen")
}
如代码片段中所述,用于标记依赖键的方法的格式至关重要;你可以(也应该)阅读 relevant documentation here .
关于Swift:计算属性的 Cocoa 绑定(bind)值不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35892657/