我有一个 NSView
子类,我想公开一个属性(准确地说是 NSGradient
),这样我就可以将它与其他对象绑定(bind)(以编程方式使用 bind:toObject:withKeyPath:options:
方法)。
我应该采取什么步骤?
这是我所做的:
+(void)initalize {
[self exposeBinding:@"gradient"];
}
- (Class)valueClassForBinding:(NSString*)binding {
if ([binding isEqualToString:@"gradient"]) { return([NSGradient class]); }
return(nil);
}
-(NSArray*)exposedBindings {
return([NSArray arrayWithObjects:@"gradient",nil]);
}
我不介意绑定(bind)是否未显示在界面生成器中。
gradient
是使用 @property(nonatomic,retain)NSGradient*gradient
实现的属性,并且在当前实现中运行良好。
仅仅需要上面的代码来实现吗? (好像太简单了) 我相信我错过了一些东西。
注意:我不是绑定(bind)专家,但我在 Objective-C 的大部分方面都做得很好。
最佳答案
要绑定(bind)的属性(property)必须符合 KVO 和 KVC 规范;这本质上就是所需要的一切。按照您的方式声明属性,然后@synthesize
它们或执行类似的操作就足够了。
bind:toObject:withKeyPath:options:
由于某种原因只有一种方式,因此您必须像 Tom Dalling 所说的那样使用 KVC 来传播值。对 -bind:etc
消息接收者所做的更改必须手动传播。
据我所知,-exposeBinding:
在 Xcode 4 中并没有真正执行任何操作,并且没有必要,因为 IB 不再支持插件。来自 documentation :
In most cases you need to use bind:toObject:withKeyPath:options:, and then only when you establish bindings programatically. Use of the unbind: is discussed in “Unbinding.” The other methods—the class method exposeBinding: and the instance methods exposedBindings and valueClassForBinding:—are useful only in an Interface Builder palette.
据我所知,只要您使用 -bind:toObject:withKeyPath:options:
,您发布的大部分代码都是不必要的。您可以保留该代码以在 Interface Builder 中公开绑定(bind),但由于现在已经是 2012 年了,IB 不再有插件...
关于objective-c - 在自定义 NSView 上手动公开绑定(bind)需要什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10954419/