Disable/Enable NSButton if NSTextfield is empty or not

后端 未结 4 2120
清歌不尽
清歌不尽 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:29

    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 here enter image description here

提交回复
热议问题