您可能有其他原因来检查输入。(我认为与 '\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;
}