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