- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
NSLog(@"%@",string);
NSLog(@"%ld",(long)range.location);
//判断多个小数点
if ([textField.text rangeOfString:@"."].location!=NSNotFound) {
if ([string isEqualToString:@"."]) {
NSLog(@"不能含有多个小数点");
return NO;
}
}
//删除字符
if (range.location<textField.text.length && string.length==0) {
NSLog(@"删除");
return YES;
}
//判断输入是否合法
if ([@"1234567890." rangeOfString:string].location==NSNotFound) {
NSLog(@"输入不合法");
return NO;
}
// //首个字符不能小数点
// if(range.location==0){
if ([textField.text hasSuffix:@"0"]) {
if (![string isEqualToString:@"."]) {
NSLog(@"如果第一位为0第二位必须是小数点");
return NO;
}
}
if ([string isEqualToString:@"."]) {
if (range.location==0) {
NSLog(@"首个字符不能为小数点");
return NO;
}
if (range.location>=textField.text.length) {
return YES;
}
if (range.location<textField.text.length-2) {
NSLog(@"只能保留两位小数");
return NO;
}
}
NSArray *tempArray=[textField.text componentsSeparatedByString:@"."];
if ([tempArray count]>1&&[tempArray count]<3) {
NSString *tempString=[tempArray objectAtIndex:1];
if (tempString.length>=2) {
//NSLog(@"%ld",(long)range.location);
NSRange tempRange=[textField.text rangeOfString:@"."];
if (range.location<=tempRange.location) {
return YES;
}else{
NSLog(@"小数点后面只能有两位小数");
return NO;
}
}else{
return YES;
}
}else{
return YES;
}
}