Search code examples
swiftmulti-selectappkit

Bind one NSTextField to multiple properties


I am trying to do multiple edits in an Inspector View, I have two objects selected and I would like to edit both of their houseName properties at the same time.

class House: NSObject {
    dynamic var houseName: String
}

var house1: House()
var house2: House()

houseNameTextField.bind(.value, to: house1, withKeyPath: "houseName", options: [])

If I bind the first house, I can change the property fine, however, can I bind a second property to the same textField, so when I edit the textfield, both properties get updated?

Calling .bind again simply overwrites the first binding


Solution

  • I found a solution that works for me, I needed to create an ArrayController and use the "selection" key, it magically works

    let options: [NSBindingOption : Any] = [NSBindingOption.validatesImmediately: true,
                                            NSBindingOption.allowsEditingMultipleValuesSelection: true,
                                            NSBindingOption.multipleValuesPlaceholder: "Multiple",
                                            NSBindingOption.nullPlaceholder: "None",
                                            NSBindingOption.conditionallySetsEditable: true]
    
    houseNameTextField.bind(.value, to: arrayController, withKeyPath: "selection.houseName", options: options)