Search code examples
swiftcocoabindingnsbutton

NSButton Title not updating when bound value changes


What I would like to do is bind the Title of a NSButton so I can change the title of button by changing the value of the variable it is bound to.

I have created the default swift cocoa app project and added two buttons to the window. ButtonA and ButtonB.

For the Value binding of ButtonB, I have bound the Title to the App Delegate with the model key path set to self.buttonBTitleBinding.

I have set the action of ButtonA to the app delegate function buttonA.

I have defined the app delegate as follows:

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
    }
}

When I launch the application, the title of button B is "Hello", so I know it is bound to the correct variable.

When I press button A, I do see in the console:

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

I know that didSet for buttonBTitleBinding is being called and that it's value is changing.

However, the title of the button does not update.

Is there a way to make this work?


Solution

  • For bindings to work, the property has to be changed in a KVO way. I'm new to Swift but I found this: Is key-value observation (KVO) available in Swift?. In short: add the dynamic modifier to the property.