iOS UITextField 输入含小数的数字(位数限制)

//1.先实例化textField,然后代理设为自己
//2.textField.text是存在字符   string是输入字符
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{

  //对复制黏贴也有效  
   int location = (int)[mInputMoney.text rangeOfString:@"."].location;
    if (location > 0) {
        isHavePoint = YES; //isHavePoint 是BOOL型
    }else
    {
        isHavePoint = NO;
    }

    if ([string length] > 0) {
        unichar single = [string characterAtIndex:0];//输入的字符
        if ((single >= '0' && single <= '9') || single == '.')//输入格式正确
        {
            if ([mInputMoney.text length] == 0) {
                if (single == '.') {
                    [self.view makeToast:@"亲,第一个数字不能为小数点"];
                    return NO;
                }
                    if (single == '0') {
                        [self.view makeToast:@"亲,第一个数字不能为0"];
                        return NO;
                    }
            }
            if (single == '.') {
                if (!isHavePoint) {
                    isHavePoint = YES;
                    return YES;
                }
                if (isHavePoint) {
                    [self.view makeToast:@"亲,您已经输入过小数点了"];
                    return NO;
                }
            }else
            {
                //判断小数点的位数
                if (isHavePoint) {
                    NSRange pointRange = [mInputMoney.text rangeOfString:@"."];
                    int location = (int)range.location - (int)pointRange.location;
                    if (location <= 2) {
                        return YES;
                    }else
                    {
                        [self.view makeToast:@"亲,您最多输入两位小数"];
                        return NO;
                    }
                }else
                {
                    return YES;
                }
            }
        }else
        {
            [self.view makeToast:@"亲,您输入的格式不正确"];
            return NO;
        }
    }else
    {
        return YES;
    }
    return YES;
}
//限制11位和对删除字符的判断
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{

   if ([string isEqualToString:@""] && range.length > 0) {//输入删除字符
            return YES;
        }
   if (textField.text.length >= 11) {
            return NO;
        }

  return YES;
}

你可能感兴趣的:(UITextField)