转载:http://blog.csdn.net/u010070526/article/details/50766679
和http://www.jianshu.com/p/aeafd022869c
(1)
一、限制只能输入数字,但输入错误没有提示只是不显示
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *result = [textField.text stringByReplacingCharactersInRange:range withString:string];
if (result.length == 0) return YES;
NSString *regex = @"^[1-9][0-9]*$";
NSPredicate *prd = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex]; return [prd evaluateWithObject:result];
}
二、限制只能输入数字,但输入错误会有提示1.定义常量以备使用?1#define NUMBERS @"0123456789"2、实现代理方法[html] view plain copy 在CODE上查看代码片派生到我的代码片
- (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)string
{
NSCharacterSet*cs;
cs = [[NSCharacterSetcharacterSetWithCharactersInString:NUMBERS] invertedSet];
NSString*filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
BOOLbasicTest = [string isEqualToString:filtered];
if(!basicTest) {
UIAlertView* alert = [[UIAlertViewalloc] initWithTitle:@"提示"
message:@"请输入数字"
delegate:nil
cancelButtonTitle:@"确定"
otherButtonTitles:nil];
[alert show];
returnNO;
}
returnYES;
}