下面这个限制输入金额限制得很死:
- 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 }else38 {39 [textField.text stringByReplacingCharactersInRange:range withString:@""];40 return NO;41 }42 }43 else44 {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 else57 {58 return YES;59 }60 }61 }else{ //输入的数据格式不正确62 [textField.text stringByReplacingCharactersInRange:range withString:@""];63 return NO;64 }65 }66 else67 {68 return YES;69 }70 }71 }