如果用户使用的是苹果自带键盘,则使用labelName.keyboardType = UIKeyboardTypeNumberPad;就可以实现只能输入数字,但是,如果用户手机使用的是自己下载的输入法,则使用下面方法实现只能输入数字
- (BOOL)textField:(UITextField*)textField
shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)string
{
return
[selfvalidateNumberByRegExp:string];
}
//限制只能输入数字
- (BOOL)validateNumberByRegExp:(NSString*)string
{
BOOL isValid = YES;
NSUInteger len = string.length;
if (len > 0) {
NSString *numberRegex = @"^[0-9.]*$";
NSPredicate *numberPredicate = [NSPredicatepredicateWithFormat:@"SELF MATCHES %@", numberRegex];
isValid = [numberPredicate evaluateWithObject:string];
}
return isValid;
BOOL isValid = YES;
NSUInteger len = string.length;
if (len > 0) {
NSString *numberRegex = @"^[0-9.]*$";
NSPredicate *numberPredicate = [NSPredicatepredicateWithFormat:@"SELF MATCHES %@", numberRegex];
isValid = [numberPredicate evaluateWithObject:string];
}
return isValid;
}
本文介绍了一种在iOS应用中限制用户仅能输入数字的方法。通过使用正则表达式验证输入内容,确保无论用户使用何种输入法,都只能输入数字字符。
1167

被折叠的 条评论
为什么被折叠?



