收听我的文本字段的值更改 [英] Listen to a value change of my text field

查看:37
本文介绍了收听我的文本字段的值更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试了解如何从窗口中的文本字段捕获文本更改"事件.我习惯了 Java 的动作监听器",在 Objective-C/Cocoa 中找不到类似的东西.我搜索了很长时间,找到了键值观察"协议,但是 observeValueForKeyPath: 方法(函数?)仅在代码中更改我的文本字段的值时触发(使用 [textfield setStringValue:...],例如),而不是通过输入.

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?

推荐答案

您可以为您的 NSTextField 实例设置一个委托,并让该委托实现以下方法:

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];

或者,在 Interface Builder 中,通过 NSTextField 控件中可用的 delegate 出口.

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

请注意,如果有多个控件挂钩到同一个委托,则将为每个控件发送 -controlTextDidChange:,即,为不同的控件调用相同的方法.如果你想根据文本改变的控件有不同的行为,你可以使用-[NSNotification object]来识别发送通知的控件.

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.

例如,如果您有两个文本字段和相应的出口 nameFieldaddressField,并且您为这两个字段设置了相同的委托,则:

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

或者,您可以为每个文本字段指定一个代表.在这种情况下,就不需要测试 [notification object].

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

这篇关于收听我的文本字段的值更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆