Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
668 views
in Technique[技术] by (71.8m points)

objective c - Listen to a value change of my text field

I'm trying to understand how to catch a "text changed" event from a text field in my window. I'm used to Java's "action listeners", and can't find anything similar in Objective-C/Cocoa. I searched for quite a while and found the "key value observing" protocol, but the observeValueForKeyPath: method (function?) only triggers when the value of my text field was changed in code (using [textfield setStringValue:...], e.g.), not by typing in it.

How can I "listen" to the value change when a user types in the text field?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can set a delegate for your NSTextField instance and have the delegate implement the following method:

- (void)controlTextDidChange:(NSNotification *)notification {
    // there was a text change in some control
}

Your delegate object can be the application delegate, a window controller, a view controller, or some other object in your application. The delegate can be programatically set via

[myTextField setDelegate:delegateObject];

or, in Interface Builder, via the delegate outlet available in the NSTextField control.

Note that if there are multiple controls hooked to the same delegate then -controlTextDidChange: will be sent for each control, i.e., the same method is called for different controls. If you want different behaviour according to the control where the text has changed, you can use -[NSNotification object] to identify the control that has sent the notification.

For instance, if you have two text fields with corresponding outlets nameField and addressField, and you’ve set the same delegate for both fields, then:

- (void)controlTextDidChange:(NSNotification *)notification {
    // there was a text change in some control
    // [notification object] points to the control that has sent
    // the notification

    if ([notification object] == nameField) {
        // nameField has changed
    }
    else if ([notification object] == addressField) {
        // addressField has changed
    }
}

Alternatively, you could have one delegate for each text field. In this case, there’d be no need to test [notification object].


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...