0

Using cocoa bindings, I want that a popup button is enabled or disabled based on whether the checkbox is selected or not.

I am programatically adding checkboxes and popups to a stack view like this:

  private func addCheckBoxes() {
        for period in String.BuildTimePeriod.allCases {
            let checkbox = NSButton(checkboxWithTitle: period.rawValue.capitalized, target: self, action: nil)
            checkbox.bind(.value, to: NSUserDefaultsController.shared, withKeyPath: "values.\(period.defaultsBoolKey.rawValue)", options: [NSBindingOption.continuouslyUpdatesValue: true])
            stackView.addArrangedSubview(checkbox)
            addPopUpToCheckbox(checkbox, period: period)
        }
    }

    private func addPopUpToCheckbox(_ checkbox: NSButton, period: String.BuildTimePeriod) {
        let popUp = NSPopUpButton(frame: checkbox.frame, pullsDown: false)
        let timeBlocks = String.TimeBlock.allCases.map() { $0.rawValue.capitalized }
        popUp.addItems(withTitles: timeBlocks)
        popUp.bind(.selectedValue, to: NSUserDefaultsController.shared, withKeyPath: "values.\(period.rawValue)", options: [NSBindingOption.continuouslyUpdatesValue: true])
        popUp.bind(.enabled, to: checkbox, withKeyPath: "state", options: [NSBindingOption.continuouslyUpdatesValue : true])
        stackView.addArrangedSubview(popUp)
    }

The binding works on initial load, of the controller, however, the popUps enabled state do not change dynamically. Wondering if anyone can provide any guidance.

Henry Cooper
  • 97
  • 1
  • 2
  • 10
  • 1
    Possible duplicate of [Cocoa: How to bind a boolean property to NSCellStateValue?](https://stackoverflow.com/questions/11193804/cocoa-how-to-bind-a-boolean-property-to-nscellstatevalue) – Willeke Jul 10 '19 at 14:56
  • fixed my problem. Great find and thanks! – Henry Cooper Jul 10 '19 at 15:00

1 Answers1

0

Thanks to @Willeke, I realised it was because I was simply referencing "state", rather than "cell.state" which is what is needed for buttons.

Henry Cooper
  • 97
  • 1
  • 2
  • 10