I send the willChangeValueForKey: and didChangeValueForKey:, but the UI doesn't update to the new values while that text field is still active.
有发送这些消息很少的原因。通常,通过实现和使用访问器(或更好的属性),您可以更好,更干净地完成同样的工作。 KVO会在你这样做的时候为你发送通知。
在你的情况下,你想要拒绝或过滤虚假输入(如“12abc”)。此任务的正确工具是键值验证。
要启用此功能,请检查IB中绑定的“立即验证”框,并实施验证方法。
过滤:
- (BOOL) validateMyValue:(inout NSString **)newValue error:(out NSError **)outError {
NSString *salvagedNumericPart;
//Determine whether you can salvage a numeric part from the string; in your example, that would be “12”, chopping off the “abc”.
*newValue = salvagedNumericPart; //@"12"
return (salvagedNumericPart != nil);
}
拒绝:
- (BOOL) validateMyValue:(inout NSString **)newValue error:(out NSError **)outError {
BOOL isEntirelyNumeric;
//Determine whether the whole string (perhaps after stripping whitespace) is a number. If not, reject it outright.
if (isEntirelyNumeric) {
//The input was @"12", or it was @" 12 " or something and you stripped the whitespace from it, so *newValue is @"12".
return YES;
} else {
if (outError) {
*outError = [NSError errorWithDomain:NSCocoaErrorDomain code: NSKeyValueValidationError userInfo:nil];
}
//Note: No need to set *newValue here.
return NO;
}
}
(I've also noticed that the setter method receives an NSString, not an NSNumber. Is that normal?)
是的,除非你使用值转换器是转换字符串到数字,一个数字格式化连接到formatter
出口,或替代验证方法中的NSString的NSNumber。
我掉到地上的文本字段添加了一个数字格式化为你指出的文档建议,但没有任何反应。我仍然可以键入非数字字符。除了将格式器连接到文本字段之外,我还需要做什么? – lajos 2009-02-09 17:23:18