先写好代理,然后新建一个BOOL类型的isHaveDian
#pragma mark- UITextFieldDelegate
//在这个代理方法中
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField.keyboardType == UIKeyboardTypeDecimalPad) {
if ([textField.text rangeOfString:@"."].location==NSNotFound) {
self.isHaveDian=NO;
}
if ([string length]>0)
{
unichar single=[string characterAtIndex:0];//当前输入的字符
if ((single >='0' && single<='9') || single=='.')//数据格式正确
{
//如果要判断输入的数不能大于某一个值,用以下方法
if ([[NSString stringWithFormat:@"%@%@",textField.text,string] doubleValue]>100) {
//大于总金额
return NO;
}
//首字母不能为0和小数点
if([textField.text length]==0){
if(single == '.'){
// [self alertView:@"亲,第一个数字不能为小数点"];
[textField.text stringByReplacingCharactersInRange:range withString:@""];
return NO;
}
}else if (textField.text.length == 1 && [textField.text isEqualToString:@"0"]){
if (single != '.') {
// [self alertView:@"亲,第一个数字不能为0"];
[textField.text stringByReplacingCharactersInRange:range withString:@""];
return NO;
}
}
if (single=='.')
{
if(!self.isHaveDian)//text中还没有小数点
{
self.isHaveDian=YES;
return YES;
}else
{
// [self alertView:@"亲,您已经输入过小数点了"];
[textField.text stringByReplacingCharactersInRange:range withString:@""];
return NO;
}
}
else
{
if (self.isHaveDian)//存在小数点
{
//判断小数点的位数
NSRange ran=[textField.text rangeOfString:@"."];
NSInteger tt=range.location-ran.location;
if (tt <= 2){
return YES;
}else{
// [self alertView:@"亲,您最多输入两位小数"];
return NO;
}
}
else
{
return YES;
}
}
}else{//输入的数据格式不正确
// [self alertView:@"亲,您输入的格式不正确"];
[textField.text stringByReplacingCharactersInRange:range withString:@""];
return NO;
}
}
else
{
return YES;
}
}
return YES;
}
网友评论