0

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?

ericg
  • 8,413
  • 9
  • 43
  • 77
  • 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?](http://stackoverflow.com/questions/24092285/is-key-value-observation-kvo-available-in-swift). In short: add the `dynamic` modifier to the property. – Willeke Dec 10 '15 at 15:17
  • If you would like to add this as an answer, I will mark it as such. – ericg Dec 10 '15 at 15:21

1 Answers1

1

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.

Community
  • 1
  • 1
Willeke
  • 14,578
  • 4
  • 19
  • 47