Search code examples
cocoaswiftstoryboardcocoa-bindings

How can I bind the text in a NSTextField to the value of a property on a controller using a storyboard?


I have a custom view with two text subviews, arranged, not that it matters, as per this amazing ASCII art:

/--------\
| lblOne |
| lblTwo |
\--------/

On my controller, I have a property of type Thingy:

class AwesomeController: NSViewController {
    var thingy: Thingy! = nil
}

A Thingy has two properties of interest:

class Thingy: NSObject {
    var one: String
    var two: String
}

I would like to set up a binding between lblOne's string value and thingy.one, and lblTwo's string value and thingy.two, going through a custom view class if necessary.

When thingy is changed, obviously the two text fields should also change. (In other words, it should behave normally for a cocoa binding.)


I think it's probably a combination of learning Swift and my unfamiliarity with storyboards on OS X (last time I did cocoa development, it was still xibs), but I can't work out how to link the damn thing up.


Solution

  • Getting bindings to work in Swift requires two additional steps:

    1. All the vars must be marked with dynamic, eg:

      dynamic var one: String

    2. You have to recompile the project (with cmd+B, not just in the background) in order for the var to appear as an option in IB