views:

131

answers:

3

Hello!

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...

A: 

There is a binding, that's the UITextField's delegate.

Then in your code, you can use the methods that will be called when the text changes to update your button's state. Your button should also be an IBOutlet obviously.

jv42
I´ve tried something like this but it doesn´t work.
Azpiri
Have you traced the execution with a breakpoint inside the delegate method? This method *should* work.
jv42
jv42: The questioner is asking about NSTextField (Cocoa), not UITextField (Cocoa Touch).
Peter Hosey
Oh, sorry about that, misread the question. I suppose I'm too deep into iPhone programming these days ;-)
jv42
A: 

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.

Peter Hosey
A: 

Thanks Peter. What I missed (in my hard way version) is this piece of code in the awakeFromNib in the appDelegate:

NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self selector:@selector(textDidChange:) name:NSControlTextDidChangeNotification object:myTextField];

It works perfect. Now I´m trying the easy way, but I´m afraid I´m not still good enough with the bindings.

To bind the property

@property (retain) IBOutlet NSString *aStringValue;

with the textfield´s value, what I have to use in IB for "Bind to:", "Controller Key" and "Model Key Path"?

Azpiri