As it stands, you're observing changes in the text1
property, and not it's stringValue
, and even then that only works when setStringValue:
is called explicitly (it isn't called by the input context for the field). You'd be better off becoming it's delegate and implementing controlTextDidChange:
, rather than trying to KVO the thing.
How to create KVO for a TextField [Mac OS]?
-
30-07-2022 - |
题
I need to create KVO for TextField1 and when changing its value transfer value of TextField1 to TextFiled2. I tried so:
//.h
@property (weak) IBOutlet NSTextFieldCell *text1;
@property (weak) IBOutlet NSTextFieldCell *text2;
//.m
-(id) init
{
self = [super init];
if (self)
{
[self addObserver:self forKeyPath: @"text1" options:NSKeyValueObservingOptionOld context:nil];
}
return self;
}
-(void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
[self.text2 setStringValue:[self.text1 stringValue]];
}
It does not work. Where is a mistake?
解决方案
不隶属于 StackOverflow