键值绑定在iOS中并不存在,但您必须手动执行。您可以创建一个从“Button”派生的类,您可以创建一个NSDictionary属性,您可以分配它,在分配时,您可以开始观察dictionary实例中的更改,并在委托中读取值并分配给self。
好的,这是我的button.h文件
@interface MyCustomButton : NSButton
NSDictionary* store;
@end
-(NSDictionary*) store;
-(void) setStore: (NSDictionary*) v;
这是我的button.m文件
@implementation MyCustomButton
-(void) dealloc{
[self setStore: nil];
[super dealloc];
}
-(void) loadValues:{
// fill your loading values here
// this is not correct you may need
// to see help to get correct names of
// function
[self setText: [store stringForKey:@"buttonLabel"]];
}
-(void) setStore: (NSDictionary*) v{
if(store!=nil){
[store removeObserver: self forKeyPath:@"buttonLabel"];
[store removeObserver: self forKeyPath:@"buttonX"];
[store removeObserver: self forKeyPath:@"buttonY"];
[store release];
}
if(v==nil)
return;
store = [v retain];
[store addObserver: self forKeyPath:@"buttonLabel" options:0 context:nil];
[store addObserver: self forKeyPath:@"buttonX" options:0 context:nil];
[store addObserver: self forKeyPath:@"buttonY" options:0 context:nil];
[self loadValues];
}
-(NSDictionary*) store{
return [store autorelease];
}
-(void) observeValueForKeyPath: (NSString*) keyPath
ofObject:(id)object
change:(NSDictionary*)change
context:(void*)context{
// here you can identify which keyPath
// changed and set values for yourself
[self loadValues];
}
@end
MyButton* button = [[[MyButton alloc] init] autorelease];
// add button to view...
[button setStore: myDictionary];
// from this point onwards button will automatically
// change its properties whenever dictionary
// is modified