UITextField 限制输入金额(项目中遇到判断输入金额)

下面这个限制输入金额限制得很死:

  •  1.要求用户输入首位不能为小数点;
  • 2.小数点后不超过两位,小数点无法输入超过一个;
  • 3.如果首位为0,后面仅能输入小数点;
  • 4.输入金额不超过11位。

 

1 -(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
 2 {
 3     if (textField.text.length > 10) {
 4         return range.location < 11;
 5     }else{
 6         BOOL isHaveDian = YES;
 7         if ([textField.text rangeOfString:@"."].location==NSNotFound) {
 8             isHaveDian=NO;
 9         }
10         if ([string length]>0)
11         {
12             unichar single=[string characterAtIndex:0];//当前输入的字符
13             
14             if ((single >='0' && single<='9') || single=='.')//数据格式正确
15             {
16                 //首字母不能为小数点
17                 if([textField.text length]==0){
18                     if(single == '.'){
19                         [textField.text stringByReplacingCharactersInRange:range withString:@""];
20                         return NO;
21                         
22                     }
23                 }
24                 if([textField.text length]==1 && [textField.text isEqualToString:@"0"]){
25                     if(single != '.'){
26                         [textField.text stringByReplacingCharactersInRange:range withString:@""];
27                         return NO;
28                         
29                     }
30                 }
31                 if (single=='.')
32                 {
33                     if(!isHaveDian)//text中还没有小数点
34                     {
35                         isHaveDian=YES;
36                         return YES;
37                     }else
38                     {
39                         [textField.text stringByReplacingCharactersInRange:range withString:@""];
40                         return NO;
41                     }
42                 }
43                 else
44                 {
45                     if (isHaveDian)//存在小数点
46                     {
47                         //判断小数点的位数
48                         NSRange ran=[textField.text rangeOfString:@"."];
49                         NSInteger tt=range.location-ran.location;
50                         if (tt <= 2){
51                             return YES;
52                         }else{
53                             return NO;
54                         }
55                     }
56                     else
57                     {
58                         return YES;
59                     }
60                 }
61             }else{//输入的数据格式不正确
62                 [textField.text stringByReplacingCharactersInRange:range withString:@""];
63                 return NO;
64             }
65         }
66         else
67         {
68             return YES;
69         }
70     }
71 }

 

posted @ 2016-06-24 11:18  Crazy_ZY  阅读(397)  评论(0编辑  收藏  举报