@interface ViewController ()<UITextFieldDelegate>
{ BOOL isHaveDian;}@end
1 - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 2 { 3 if ([textField.text rangeOfString:@"."].location == NSNotFound) { 4 isHaveDian = NO; 5 } 6 if ([string length] > 0) { 7 8 unichar single = [string characterAtIndex:0];//当前输入的字符 9 if ((single >= '0' && single <= '9') || single == '.') { //数据格式正确10 11 //首字母不能为0和小数点12 if([textField.text length] == 0){13 if(single == '.') {14 [self showError:@"亲,第一个数字不能为小数点"];15 [textField.text stringByReplacingCharactersInRange:range withString:@""];16 return NO;17 }18 if (single == '0') {19 [self showError:@"亲,第一个数字不能为0"];20 [textField.text stringByReplacingCharactersInRange:range withString:@""];21 return NO;22 }23 }24 25 //输入的字符是否是小数点26 if (single == '.') {27 if(!isHaveDian)//text中还没有小数点28 {29 isHaveDian = YES;30 return YES;31 32 }else{33 [self showError:@"亲,您已经输入过小数点了"];34 [textField.text stringByReplacingCharactersInRange:range withString:@""];35 return NO;36 }37 }else{38 if (isHaveDian) { //存在小数点39 40 //判断小数点的位数41 NSRange ran = [textField.text rangeOfString:@"."];42 if (range.location - ran.location <= 2) {43 return YES;44 }else{45 [self showError:@"亲,您最多输入两位小数"];46 return NO;47 }48 }else{49 return YES;50 }51 }52 }else{ //输入的数据格式不正确53 [self showError:@"亲,您输入的格式不正确"];54 [textField.text stringByReplacingCharactersInRange:range withString:@""];55 return NO;56 }57 }58 else59 {60 return YES;61 }62 }
1 - (void)showError:(NSString *)errorString2 {3 [(AppDelegate *)[UIApplication sharedApplication].delegate showErrorView:errorString];4 [NSTimer scheduledTimerWithTimeInterval:2.0f target:self selector:@selector(removeErrorView2) userInfo:nil repeats:NO];5 6 [self.moneyTf resignFirstResponder];7 }