-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { if (textField.text.length > 10) { return range.location < 11; }else{ BOOL isHaveDian = YES; if ([textField.text rangeOfString:@"."].location==NSNotFound) { isHaveDian=NO; } if ([string length]>0) { unichar single=[string characterAtIndex:0];//当前输入的字符 if ((single >='0' && single<='9') || single=='.')//数据格式正确 { //首字母不能为小数点 if([textField.text length]==0){ if(single == '.'){ [textField.text stringByReplacingCharactersInRange:range withString:@""]; return NO; } } if([textField.text length]==1 && [textField.text isEqualToString:@"0"]){ if(single != '.'){ [textField.text stringByReplacingCharactersInRange:range withString:@""]; return NO; } } if (single=='.') { if(!isHaveDian)//text中还没有小数点 { isHaveDian=YES; return YES; }else { [textField.text stringByReplacingCharactersInRange:range withString:@""]; return NO; } } else { if (isHaveDian)//存在小数点 { //判断小数点的位数 NSRange ran=[textField.text rangeOfString:@"."]; NSInteger tt=range.location-ran.location; if (tt <= 2){//2表示小数点后能输入两位,4就是能输入4位 return YES; }else{ return NO; } } else { return YES; } } }else{//输入的数据格式不正确 [textField.text stringByReplacingCharactersInRange:range withString:@""]; return NO; } } else { return YES; } } }
参考:https://www.cnblogs.com/fcug/p/5500349.html
标签:string,text,length,single,UITextField,textField,输入,小数 From: https://www.cnblogs.com/qingzZ/p/17378101.html