Disable/Enable NSButton if NSTextfield is empty or not

后端 未结 4 2119
清歌不尽
清歌不尽 2021-02-08 01:05

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 po

4条回答
  •  一生所求
    2021-02-08 01:49

    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.

提交回复
热议问题