2

我有一个快速的问题,我在任何地方都找不到。我将我的文本字段限制为数字、小数和负号。但在这样做时,我关闭了返回键。有人知道 iOS 的返回键的 unichar 编号吗?我以为是十三岁,但那行不通。

 - (BOOL)textField:(UITextField *)textField 
 shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
 {
     NSUInteger lengthOfString = string.length;
for (NSInteger loopIndex = 0;  loopIndex < lengthOfString; loopIndex++)
     {
         unichar character = [string characterAtIndex:loopIndex]; 
         if (character < 45) return NO; //45 - 57 we want
         if (character > 57) return NO; // -./0123456789
         if (character == 47) return NO; //47 we dont want, it is 
 //             if (character  == 36) return YES
     }
NSUInteger newLength = [textField.text length] + [string length] - range.length;
return (newLength > 5) ? NO : YES;
 }
4

2 回答 2

2

您可能有其他原因来检查输入。(我认为与 '\n' 作品相比),但这可能会更好:

-(BOOL)textFieldShouldReturn:(UITextField *)textField

编辑

处理浮点输入的更彻底的处理可能如下所示。关键思想是用建议的替换来构建一个候选字符串,然后测试整个字符串的语法有效性。通过这种方式,您可以处理用户在任意位置粘贴新文本而无需接触代码。正则表达式只是一种指定语法的紧凑/快速方法,您可以将自己的方法放入验证器中。

(我猜您可能希望将减号处理为不是字面上输入的一部分,而是需要负数的指示符。还假设长度限制是有效数字,而不仅仅是总字符)

// answers true for a valid floating point literal, notwithstanding length
- (BOOL)isValidFloat:(NSString *)string {

    // optional sign, followed by zero or more digits, followed by decimal, followed by zero or more digits
    NSString *regex = @"([-+]?[0-9]*\\.?[0-9]*)";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return [predicate evaluateWithObject:string];
}

#define kMAX_DIGITS  5

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

    NSString *currentText = textField.text;
    NSString *candidateText = [currentText stringByReplacingCharactersInRange:range withString:string];

    // accept a minus sign at any time. Place it in front if it's not already there
    if (string.length == 1 && [string characterAtIndex:0]=='-') {
        if ([currentText rangeOfString:string].location == NSNotFound) {
            textField.text = [string stringByAppendingString:currentText];
            // since we just inserted the minus, answer no so it won't be inserted twice
            return NO;
        }
    }

    // the decimal and minus sign don't count against the length constraint
    NSInteger decimalFudge = ([candidateText rangeOfString:@"."].location != NSNotFound)? 1 : 0;
    NSInteger minusFudge = (candidateText.length > 0 && [candidateText characterAtIndex:0]=='-')? 1 : 0;
    NSInteger maxLength = kMAX_DIGITS + decimalFudge + minusFudge;

    return (candidateText.length <= maxLength) && [self isValidFloat:candidateText];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}
于 2012-04-29T23:59:52.683 回答
1

KeyCode 36 号呢?

看看这个链接的答案: NSTextField captures return key event两次

无论如何,您可以禁用这些限制并对每个输入键执行 NSLog 以获得返回的 unichar 数。

于 2012-04-29T23:58:32.190 回答