How to bind a checkbox's enabled status to the value of an NSTextField

This is a noobie question related to bindings which has probably been asked before, but I have not found a straightforward solution thus far.

The desired behavior is fairly simple. I have a checkbox whose enabled status I would like to bind to the value of an NSTextField. When the NSTextField’s value is the empty string, I would like the checkbox to be disabled, and when the value is anything but the empty string, I would like the checkbox to be enabled. The built-in value transformer NSIsNotNil works fine if the NSTextField’s value is the missing value but not if it is the empty string. I can conceive how this can be accomplished via other means (outlets, delegates), but I would like to accomplish this with bindings for two reasons: (1) to minimize the amount of code, and (2) to become more facile with bindings and NSValueTransformer (which I presume is involved in the solution).

Thank you for any assistance.

Hi,

I recommend to use key value observing.
Implement this code


property textFieldValue : ""

on keyPathsForValuesAffectingEnableCheckbox()
    return current application's NSSet's setWithObject:"textFieldValue"
end keyPathsForValuesAffectingEnableCheckbox

on enableCheckbox()
    return my textField's stringValue()'s |length|() > 0
end enableCheckbox

bind Value of the text field to key path textFieldValue
bind Enabled of the check box to key path enableCheckbox

the two handlers manage the key value observing.
The naming convention is

keyPathsForValuesAffecting<KeyPath>() <keyPath>()

Amazing, Stephan, it works, thank you! I made one slight adjustment that accomplishes the same result, namely

return my textFieldValue's length > 0

rather than

return my textField's stringValue()'s |length|() > 0

because in my code I have textFieldValue bound to the value of the NSTextField but no textField outlet to the NSTextField.

May I ask a couple of follow-up questions:

(1) Am I correct in thinking that for multiple independent NSTextField-checkbox pairs, I would have to set up separate handlers for each NSTextField-chekcbox pair, e.g., keyPathsForValuesAffectingEnableCheckbox1 and enableCheckbox1, keyPathsForValuesAffectingEnableCheckbox2 and enableCheckbox2, …?

(2) If that is the case, and if there are a quite a few NSTextField-checkbox pairs, would it possibly be simpler to use an NSValueTransformer solution, and apply the same NSValueTransformer to the enabled status of each of the checkboxes?

Thank you again for the awesome solution.

(Note: I clarified my comments about textFieldValue and textField in this edited reply.)

yes, of course. I tried first to observe the key path textField.stringValue but that didn’t work.

yes, indeed.

the value transformer solution is probably better with multiple occurrences.