我正在制作一个具有以下特征的NSTextField:
1)仅允许整数值(0-9)
2)长度为1或2位
3)min为1,最大为99
4)如果输入0,则值应更改回1
5)如果按下删除并且单元格完全清空,则该值应更改为1并自动选择(高亮显示),以便用户只需键入新值
我可以通过创建自定义格式化程序和委托来获得此行为,但我想仅在自定义格式化程序中实现此功能(以保持“简单”我认为)。
这是我的代码:
在委托文件中:
- (void)controlTextDidChange:(NSNotification *)aNotification
{
if ([[txtfldSaveDuration stringValue] length]==0) {
[txtfldSaveDuration setStringValue:@"1"];
}
if ([[txtfldSaveDuration stringValue] isEqualToString:@"0"]) {
[txtfldSaveDuration setStringValue:@"1"];
}
}
自定义格式化程序文件中的:
@implementation OnlyIntegerValueFormatter
- (BOOL)isPartialStringValid:(NSString*)partialString newEditingString: (NSString**)newString errorDescription:(NSString**)error
{
// necessary otherwise can't delete (to select) the first character
if([partialString length] == 0) {
return YES;
}
// two integer max length (99)
if([partialString length] > 2) {
return NO;
}
// integers only
NSScanner* scanner = [NSScanner scannerWithString:partialString];
if(!([scanner scanInt:0] && [scanner isAtEnd])) {
NSBeep();
return NO;
}
return YES;
}
@end
我该如何简化?
答案 0 :(得分:2)
如果改为实施-isPartialStringValid:proposedSelectedRange:originalString:originalSelectedRange:errorDescription:
,您将获得更多控制权,包括在所选范围内。
可能类似于:
- (BOOL)isPartialStringValid:(NSString **)partialStringPtr
proposedSelectedRange:(NSRangePointer)proposedSelRangePtr
originalString:(NSString *)origString
originalSelectedRange:(NSRange)origSelRange
errorDescription:(NSString **)error
{
if ([*partialStringPtr length] == 0)
{
*partialStringPtr = @"1";
*proposedSelRangePtr = NSMakeRange(0, [*partialStringPtr length]);
return NO;
}
// two integer max length (99)
if ([*partialStringPtr length] > 2)
{
NSRange changed = NSMakeRange(origSelRange.location, [*partialStringPtr length] - (origString.length - origSelRange.length));
NSRange excess;
excess.length = [*partialStringPtr length] - 2;
excess.location = changed.location + (changed.length - excess.length);
*partialStringPtr = [*partialStringPtr stringByReplacingCharactersInRange:excess withString:@""];
*proposedSelRangePtr = NSMakeRange(excess.location, 0);
return NO;
}
// integers only
NSScanner* scanner = [NSScanner scannerWithString:*partialStringPtr];
scanner.charactersToBeSkipped = nil;
if(!([scanner scanInt:0] && [scanner isAtEnd])) {
*partialStringPtr = origString;
*proposedSelRangePtr = origSelRange;
NSBeep();
return NO;
}
return YES;
}