iOS UITextFiled 限制输入数字,并且小数点只能有一个

在UITextFiled代理中加入限制

  • (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

{

// 限制第一位不能是小数点

if(textField.text.length == 0 && [string isEqualToString:@"."]) {

    //        textField.text = [textField.text substringToIndex:([textField.text length]-1)];

    return NO;

}

NSArray *arr = [textField.text componentsSeparatedByString:@"."];

//限制小数点个数不超过两位

if(arr.count >= 2 && [string isEqualToString:@"."]) {

    return NO;

}



NSMutableString * futureString = [NSMutableString stringWithString:textField.text];

[futureString  insertString:string atIndex:range.location];

NSInteger flag=0;

const NSInteger limited = 1;//小数点后需要限制的个数

for (int i = futureString.length - 1; i>=0; i--) {



    if ([futureString characterAtIndex:i] == '.') {

        if (flag > limited) {

            return NO;

        }

        break;

    }

    flag++;

}

return YES;

}

然后,设置UITextFiled数字键盘 txtField.keyboardType = UIKeyboardTypeDecimalPad;

大功告成啦,就是自己记录一下,莫要忘记了.

你可能感兴趣的:(iOS UITextFiled 限制输入数字,并且小数点只能有一个)