Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable/Enable NSButton if NSTextfield is empty or not

I´m newbie with cocoa. I have a button and a textField in my app. I want the button disabled when the textfield is empty and enabled when the user type something.

Any point to start? Any "magic" binding in Interface Builder?

Thanks

[EDITED]

I´ve tried to set the appDelegate as the NSTextfield´s delegate and added this method (myTextfield and myButton are IBOutlets):

- (void)textDidChange:(NSNotification *)aNotification
{
    if ([[myTextField stringValue]length]>0) {
        [myButton setEnabled: YES];
    }
    else {
        [myButton setEnabled: NO];
    }
}

But nothing happens...

like image 519
Azpiri Avatar asked Sep 16 '10 11:09

Azpiri


2 Answers

I´ve tried to set the appDelegate as the NSTextfield´s delegate and added this method (myTextfield and myButton are IBOutlets):

- (void)textDidChange:(NSNotification *)aNotification
{
    if ([[myTextField stringValue]length]>0) {
        [myButton setEnabled: YES];
    }
    else {
        [myButton setEnabled: NO];
    }
}

That's the hard way, but it should work just fine. Either you haven't hooked up the text field's delegate outlet to this object, you haven't hooked up the myTextField outlet to the text field, or you haven't hooked up the myButton outlet to the button.

The other way would be to give the controller a property exposing the string value, bind the text field's value binding to this stringValue property, and bind the button's enabled binding to the controller's stringValue.length.

You could also give the controller two properties, one having a Boolean value, and set that one up as dependent upon the string property, and bind the button to that. That's a cleaner and possibly more robust solution, though it is more work.

like image 51
Peter Hosey Avatar answered Nov 10 '22 09:11

Peter Hosey


Here's a solution using bindings.

Below I setup a NSTextField that is bound to the file owner's "text" property. "text" is a NSString. I was caught by "Continuously Updates Value". Thinking my solution didn't work but really it wasn't updating as the user typed, and only when the textfield lost focus.

Binding the NSTextField to the file's owner NSString text property

And now setting up bindings on the button, simply set its enabled state to the length of the file owner's text property.

Binding the NSButton's enabled state to the text property's length

Annd, the working product.

enter image description hereenter image description here

like image 11
Brad G Avatar answered Nov 10 '22 08:11

Brad G