NSTextField - 使用KVO进行输入验证?

时间:2014-07-09 07:22:45

标签: objective-c macos cocoa

我的应用中有一个NSTextField,当用户给我一些不好的输入时,我想更新输入。

另外,我已将此文本字段控件的值绑定到成员变量。我已经提取了一个最小的项目:

enter image description here

这是绑定:

enter image description here

Eveything很简单,最后在代码中我将初始值设置为Hello, World,并且我还从controlTextDidChange:实施了NSControlTextEditingDelegate方法。

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    self.text = @"Hello, World";
}

- (void)controlTextDidChange:(NSNotification *)obj
{
    NSLog(@"Changed Value: %@", [[obj object] stringValue]);
    self.text = @"What??";
}

当我开始在文本字段中输入时,我确实收到了更改通知,但文本字段中的值未更新。我想知道为什么以及如何更改文本字段中的文本值并更改self.text

PS:我知道我可以通过添加outlet该文本字段来手动设置stringValue,但我不想这样做。因为它打破了low coupling规则,对吧?

1 个答案:

答案 0 :(得分:4)

要使绑定自动验证值,有Key-Value Validation的机制。

  1. 在绑定到的对象(App Delegate)中,实现以下任一方法:

    - (BOOL) validateValue:(inout id *)ioValue forKey:(NSString *)inKey error:(out NSError **)outError;
    - (BOOL) validateText:(inout id *)ioValue error:(out NSError **)outError;
    

    第一个是通用的,将被调用到所有键,第二个将专门用于键text

  2. 启用“立即验证”复选框。

  3. 如果验证方法返回NO,将显示标准错误表,其中包含将值恢复为编辑前的值的选项,以及在模型对象中没有设置值的情况下继续编辑(App Delegate)

相关问题