Cocoa 自动更新 NSTextField 中的字典值
现在我的界面中有一个包含字符串值和 NSTextField 的字典。但是,为了更新此值,我必须单击一个按钮,然后运行更新代码。如何使其在文本字段的值发生变化时动态更新?
Right now I have a dictionary containing a string value and an NSTextField in my interface. However, in order to update this value I have to click a button that then runs the update code. How can I make it dynamically update anytime the text field's value changes?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
考虑使用Cocoa Bindings。
它们旨在使您的视图(NSTextField)与模型(字典)保持同步,而无需在其间编写所有粘合代码。它们学习起来有点棘手,但是一旦你理解了它们,它们就会非常有用。
在您的情况下,您可以将 NSTextField 的“值”绑定绑定到代码中的属性。
另一种方法是设置一个 NSTextFieldDelegate 并实现:
修改字典中的值。例如,
现在每当用户修改 NSTextField 中的文本时,文本字段都会向其委托触发此回调。这样,您可以确保字典的值始终与屏幕上显示的值相同。
如果您只希望更改在用户完成编辑后生效,您可以实现:
Look into using Cocoa Bindings.
They're designed to keep your view (NSTextField) in sync with your model (dictionary) without writing all the glue code in between. They're a bit tricky to learn, but once you understand them, they're super useful.
In your case, you'd bind the "value" binding of the NSTextField to a property in your code.
An alternative is to set up an NSTextFieldDelegate and implement:
to modify the value in the dictionary. For example,
Now whenever the user modifies the text in the NSTextField, the text field will fire this callback to its delegate. This way, you can make sure the dictionary always has the same value as what's displayed on screen.
If you only want the changes to take effect when the user is done editing, you'd implement: