【问题标题】:NSButton Title not updating when bound value changes绑定值更改时NSButton标题不更新
【发布时间】:2015-12-08 14:12:52
【问题描述】:

我想做的是绑定一个 NSButton 的标题,这样我就可以通过更改它绑定到的变量的值来更改按钮的标题。

我已经创建了默认的 swift cocoa 应用程序项目,并在窗口中添加了两个按钮。按钮 A 和按钮 B。

对于 ButtonB 的 Value 绑定,我将 Title 绑定到 App Delegate,并将模型键路径设置为 self.buttonBTitleBinding。

我已将 ButtonA 的动作设置为应用委托函数 buttonA。

我已将应用委托定义如下:

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate
{
    @IBOutlet weak var window: NSWindow!

    var buttonBTitleBinding = "Hello"
    {
        didSet
        {
            NSLog( "buttonBTitleBinding: %@", buttonBTitleBinding )
        }
    }


    @IBAction func buttonA( sender: NSButton )
    {
        if self.buttonBTitleBinding == "Hello"
        {
            self.buttonBTitleBinding = "Bye"
        }
        else
        {
            self.buttonBTitleBinding = "Hello"
        }
    }


    func applicationDidFinishLaunching(aNotification: NSNotification)
    {
        // Insert code here to initialize your application
    }



    func applicationWillTerminate(aNotification: NSNotification)
    {
        // Insert code here to tear down your application
    }
}

当我启动应用程序时,按钮 B 的标题是“Hello”,所以我知道它绑定到了正确的变量。

当我按下按钮 A 时,我确实在控制台中看到:

buttonBTitleBinding: Bye 
buttonBTitleBinding: Hello
buttonBTitleBinding: Bye 
buttonBTitleBinding: Hello
buttonBTitleBinding: Bye 
buttonBTitleBinding: Hello
buttonBTitleBinding: Bye 
buttonBTitleBinding: Hello

我知道 buttonBTitleBinding 的 didSet 正在被调用,并且它的值正在改变。

但是,按钮的标题不会更新。

有没有办法让它工作?

【问题讨论】:

  • 要使绑定起作用,必须以 KVO 方式更改属性。我是 Swift 新手,但我发现了这个:Is key-value observation (KVO) available in Swift?。简而言之:将dynamic 修饰符添加到属性中。
  • 如果你想添加这个作为答案,我会这样标记。

标签: swift cocoa binding nsbutton


【解决方案1】:

要使绑定起作用,必须以 KVO 方式更改属性。我是 Swift 新手,但我发现了这个:Is key-value observation (KVO) available in Swift?。简而言之:将dynamic modifier 添加到属性中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-24
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-15
    • 2011-02-24
    相关资源
    最近更新 更多