Cocoa 自动更新 NSTextField 中的字典值

发布于 2024-10-28 04:22:16 字数 91 浏览 5 评论 0原文

现在我的界面中有一个包含字符串值和 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

无人问我粥可暖 2024-11-04 04:22:16

考虑使用Cocoa Bindings

它们旨在使您的视图(NSTextField)与模型(字典)保持同步,而无需在其间编写所有粘合代码。它们学习起来有点棘手,但是一旦你理解了它们,它们就会非常有用。

在您的情况下,您可以将 NSTextField 的“值”绑定绑定到代码中的属性。

另一种方法是设置一个 NSTextFieldDelegate 并实现:

- (void)controlTextDidChange:(NSNotification *)aNotification

修改字典中的值。例如,

- (void)controlTextDidChange:(NSNotification *)aNotification {
   [myDictionary setValue:[myTextField stringValue] forKey:@"MYDictionaryKey"];
}

现在每当用户修改 NSTextField 中的文本时,文本字段都会向其委托触发此回调。这样,您可以确保字典的值始终与屏幕上显示的值相同。

如果您只希望更改在用户完成编辑后生效,您可以实现:

- (void)controlTextDidEndEditing:(NSNotification *)aNotification

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:

- (void)controlTextDidChange:(NSNotification *)aNotification

to modify the value in the dictionary. For example,

- (void)controlTextDidChange:(NSNotification *)aNotification {
   [myDictionary setValue:[myTextField stringValue] forKey:@"MYDictionaryKey"];
}

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:

- (void)controlTextDidEndEditing:(NSNotification *)aNotification
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文