美文网首页
textField限制只能输入数字

textField限制只能输入数字

作者: 哆啦_ | 来源:发表于2016-08-22 17:07 被阅读171次

转载: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;

}

相关文章

网友评论

      本文标题:textField限制只能输入数字

      本文链接:https://www.haomeiwen.com/subject/kslgsttx.html