How to observe the value of an NSTextField

我怕爱的太早我们不能终老 提交于 2019-12-14 03:57:31

问题


This might seem straightforward, but the following code does not work, because the "observeValueForKeyPath" function is never called, although I keep changing the text in the NSTextfield:

- (void)awakeFromNib
{
    [myNSTextField addObserver:self forKeyPath:@"value" options:NSKeyValueObservingOptionOld context:nil];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    NSLog(@"observeValueForKeyPath");
}

The log message @"observeValueForKeyPath" is never printed. I tried observing the key @"stringValue", but this does not work neither...

Am I missing something ??


回答1:


[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(textFieldDIdChange:) 
                                             name:NSControlTextDidChangeNotification 
                                           object:self.textField];



回答2:


[[NSNotificationCenter defaultCenter] addObserverForName:NSTextViewDidChangeSelectionNotification
            object:self.textView 
            queue:[NSOperationQueue mainQueue] 
            usingBlock:^(NSNotification *note){
                NSLog(@"Text: %@", self.textView.textStorage.string);
            }];


来源:https://stackoverflow.com/questions/6527321/how-to-observe-the-value-of-an-nstextfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!