iOS 判断输入的字符串为格式正确的数字
2017-07-25 本文已影响10人
杨桃wd
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if ([self.moneyTtextField.text rangeOfString:@"."].location==NSNotFound) {
self.isHaveDian=NO;
}
if ([string length]>0){
unichar single=[string characterAtIndex:0];//当前输入的字符
if([self.moneyTtextField.text length]==0){
//首字母不能为0和小数点
if(single =='.'){
[SVProgressHUD showErrorWithStatus:@"提示,第一个数字不能为小数点"];
[self.moneyTtextField.text stringByReplacingCharactersInRange:range withString:@""];
return NO;
}
if (single =='0') {
[SVProgressHUD showErrorWithStatus:@"提示,第一个数字不能为0"];
[self.moneyTtextField.text stringByReplacingCharactersInRange:range withString:@""];
return NO;
}
}
if (single=='.'){//text中还没有小数点
if(!self.isHaveDian){
self.isHaveDian=YES;
return YES;
}else{
[SVProgressHUD showErrorWithStatus:@"提示,您已经输入过小数点了"];
[self.moneyTtextField.text stringByReplacingCharactersInRange:range withString:@""];
return NO;
}
}else{//存在小数点
if (self.isHaveDian){
//判断小数点的位数
NSRange ran=[self.moneyTtextField.text rangeOfString:@"."];
int tt=range.location-ran.location;
if (tt <=2){
return YES;
}else{
[SVProgressHUD showErrorWithStatus:@"提示,您最多输入两位小数"];
return NO;
}
}
else{
return YES;
}
}
}
return YES;
}