绑定:toObject:withKeyPath:选择:是单向绑定? [英] bind:toObject:withKeyPath:options: is one-way binding?

查看:174
本文介绍了绑定:toObject:withKeyPath:选择:是单向绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个窗口:窗口A从NIB加载;并且编程方式创建窗口B中。

I have two windows: Window A is loaded from NIB; and Window B is created programmatically.

这两个窗口有一个NStextView:窗口A TextView的被绑定到属性文本模型的attributedString 使用IB ;而在窗口B中的TextView的attributedString势必文本使用模型的属性 - [NSObject的绑定:toObject:withKeyPath:选项:] 方法。

Both windows have a NStextView: the attributedString of the textview in Window A is bound to the the property text of a model using IB; while the attributedString of the textview in Window B is bound to text property of the model using -[NSObject bind:toObject:withKeyPath:options:] method.

[textview bind:@"attributedString" toObject:obj withKeyPath:@"text" options:nil];

下面是奇怪的事情:在窗口B中的TextView的确被绑定到 obj.text ,但在TextView中的变化永远不会更新到 obj.text 。但是,如果我做了窗口A的TextView的,在 obj.text 的变化和窗口B中的TextView被相应地更新。

Here is the weird thing: the textview in Window B is indeed bound to the obj.text, but the changes in the textview is never updated to obj.text. But, if I made changes in the textview of Window A, the obj.text and the textview in Window B are updated accordingly.

所以我想,在 - [NSObject的绑定:toObject:withKeyPath:选项:] 方法仅适用于单向绑定。我找不到可可单证一个明确的解释。没有任何一个有这个问题的经验?如何实现双向的code绑定?

So I am thinking, the -[NSObject bind:toObject:withKeyPath:options:] method is only for one-way binding. I couldn't find a clear explanation in the Cocoa documentations. Does any one have experience with this problem? How do you implement two-way binding in code?

推荐答案

Cocoa绑定本质上是双向的,但某些行为(如文本字段的连续/实时更新)需要特定的选项进行设置。在IB你会希望确保了连续更新值复选框被选中。要以编程方式获得等价的行为,则需要指定选项上的约束力。这可能是这个样子:

Cocoa bindings are inherently two-way, but certain behaviors (like continuous/live updating of text fields) require specific options to be set. In IB you will want to make sure that the "Continuously Updates Value" check box is checked. To get equivalent behavior programmatically, you will need to specify options on the binding. That might look something like this:

[textview bind: NSAttributedStringBinding 
      toObject: obj 
   withKeyPath: @"text" 
       options: (@{ 
                 NSContinuouslyUpdatesValueBindingOption : @YES })];

这是值得一提的是,设置当编程结合,这是值得一试的相当于IB结合,并确保你传递的所有相同的设置,以程序化的结合。举例来说,我在IB看到允许编辑多个值的选择,有条件设置可编辑和提高了不适用的键选项均默认为NSTextView的归因字符串绑定检查。这将意味着我们的计划结合或许应该的真正的样子:

[textview bind: NSAttributedStringBinding 
      toObject: obj 
   withKeyPath: @"text" 
       options: (@{ 
                 NSContinuouslyUpdatesValueBindingOption : @YES,
                 NSAllowsEditingMultipleValuesSelectionBindingOption : @YES,
                 NSConditionallySetsEditableBindingOption : @YES,
                 NSRaisesForNotApplicableKeysBindingOption : @YES })];

这篇关于绑定:toObject:withKeyPath:选择:是单向绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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