1

I have a TextField in my Cocoa application. This TextField will be sometimes filled and sometimes empty.

I want it so that when the field is empty a button is disabled. Now I check the field whenever I do some action with Core Data from where the TextField gets its value.

I'd like for it to always be checked for this.

insys
  • 1,288
  • 13
  • 26
user2414590
  • 123
  • 1
  • 7

1 Answers1

0

If the user edits the text field and brings up the field editor then you can use the following.

You can implemented the NSTextFieldDelegate protocol (which is really just the NSControlTextEditing protocol). For example, in a controller or a delegate object implement the control:textShouldEndEditing: method and use this to check the values of the new string. If the string is empty then disable the button.

// In a control object which has a reference to the NSTextField and the NSButton
- (BOOL)control:(NSControl *)control textShouldEndEditing:(NSText *)fieldEditor {
    if ([fieldEditor.string isEqualToString:@""]) 
    {
        [self.button setEnabled:NO];
        return YES;
    }

    [self.button setEnabled:YES];
    return YES;
}

Update: Sorry missed that bit about CodeData. In this case you should follow the instructions here, Disable/Enable NSButton if NSTextfield is empty or not,

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.

Community
  • 1
  • 1
Daniel Farrell
  • 9,316
  • 8
  • 39
  • 62