Swift:计算属性的 Cocoa 绑定(bind)值不起作用

标签 swift cocoa cocoa-bindings

我正在学习 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)"
    }
}

enter image description here enter image description here

当我将标签直接绑定(bind)到颜色变量时,它工作正常。

enter image description here

感谢@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/

相关文章:

swift - 选择一个单元格时取消选择并更改 Collection View 中其他单元格的背景

swift - 如何使用 Swift 检查 macOS 应用程序复选框的状态

cocoa - NSTableHeaderView 中的填充渐变无法正常工作

xcode - 防火墙阻碍 Bonjour 网络调试

swift - 当网络连接不可用时,Realm 使用本地数据库而不是同步?

ios - 如何压缩多个数据而不是多个图像?

macos - 如何用C++模拟按键和鼠标点击

objective-c - 不知道如何进行 cocoa 绑定(bind)

objective-c - Cocoa Bindings,我应该只使用 KVO 吗?

Cocoa Bindings - 为什么我会得到这些角色?