监听我的文本字段的值变化
我试图了解如何从窗口中的文本字段捕获“文本更改”事件。我习惯了 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以为
NSTextField
实例设置委托,并让该委托实现以下方法:您的委托对象可以是应用程序委托、窗口控制器、视图控制器或应用程序中的其他对象。可以通过编程方式设置委托
,或者在 Interface Builder 中通过
NSTextField
控件中提供的delegate
出口进行设置。请注意,如果有多个控件挂接到同一委托,则将为每个控件发送
-controlTextDidChange:
,即为不同的控件调用相同的方法。如果您希望根据文本发生更改的控件采取不同的行为,可以使用-[NSNotification object]
来标识发送通知的控件。例如,如果您有两个带有相应插座
nameField
和addressField
的文本字段,并且您为这两个字段设置了相同的委托,那么:或者,您可以有一个每个文本字段的委托。在这种情况下,无需测试
[通知对象]
。You can set a delegate for your
NSTextField
instance and have the delegate implement the following method: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
or, in Interface Builder, via the
delegate
outlet available in theNSTextField
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
andaddressField
, and you’ve set the same delegate for both fields, then:Alternatively, you could have one delegate for each text field. In this case, there’d be no need to test
[notification object]
.您还可以从 IB 连接到“编辑已更改”并创建操作来处理它
You can also just hook up to the "Editing Changed" from IB and create the Action to handle it
这对我有用
This works for me
您可以使用
UITextFieldDelegate
的textFieldShouldBeginEditing:
方法。在 iOS 中,侦听器称为 NSNotifications编辑
在 Objective-C 中,很多 UIObject 都有一个相应的协议类,称为“委托”,委托负责对事件做出反应。因此,为了能够响应或收到有关操作的通知,您需要实现委托及其方法。
You can use
textFieldShouldBeginEditing:
method ofUITextFieldDelegate
. In iOS listeners are called NSNotificationsEDIT
In objective-c a lot of UIObjects have a corresponding protocol class that's called "delegate" The delegate is responsible for reacting to events. So to be able to respond or to be notified about actions you need to implement the delegate and its methods.