Search code examples
cocoa-bindings

Bind NSTextField to NSDictionaryController key from code (not Storyboard)


I'm trying to setup my bindings from code for NSTextFields. I can't figure out what I put for the keyPath part of the field's bindings.

let dictCtrl = NSDictionaryController(content: myDictionary)

for key in myDictionary.keys {
    let field = NSTextField()
    field.bind(NSValueBinding, toObject: dictCtrl, withKeyPath: ???, options: nil)
}

I basically want to take every key that's in the dictionary and create an NSTestField for it, and then bind the value of that field to the dictionary's value for that key.


Solution

  • NSDictionaryController transforms the contents of a dictionary into an array of key-value pairs that can be bound to user interface items such as the columns of an NSTableView.

    The content and arranged objects of the dictionary controller are arrays of key value pairs. Create a table view and bind the cells or columns with key paths @"key" and @"value".

    If you want to use text fields, use a NSObjectController. The key paths of the bindings are the keys.