使用ReactiveCocoa限制UITextField只能输入正确的金额

代码功能:

   //0.priceTextFiled.keyboardType = UIKeyboardTypeDecimalPad;//必须

        //1.限制priceTextFiled只允许输入正确的数额 比如 0 123 123. 123.0 123.12,不合法的: 00 0.1.23 将被过滤

        //2.使用这种限制方法时,TextField不能允许移动光标(:光标能且只能在最末尾),不能允许用户使用粘贴进行输入

        //3.可以在TextField上盖一层透明Button来达到2的要求

keycode:

[priceTextFiled.rac_textSignal subscribeNext:^(NSString *x) {

        static NSInteger const maxIntegerLength=8;//最大整数位
        static NSInteger const maxFloatLength=2;//最大精确到小数位
        
        if (x.length) {
            //第一个字符处理
            //第一个字符为0,且长度>1时
            if ([[x substringWithRange:NSMakeRange(0, 1)] isEqualToString:@"0"]) {
                if (x.length>1) {
                    if ([[x substringWithRange:NSMakeRange(1, 1)] isEqualToString:@"0"]) {
                        //如果第二个字符还是0,即"00",则无效,改为"0"
                        priceTextFiled.text=@"0";
                    }else if (![[x substringWithRange:NSMakeRange(1, 1)] isEqualToString:@"."]){
                        //如果第二个字符不是".",比如"03",清除首位的"0"
                        priceTextFiled.text=[x substringFromIndex:1];
                    }
                }
            }
            //第一个字符为"."时,改为"0."
            else if ([[x substringWithRange:NSMakeRange(0, 1)] isEqualToString:@"."]){
                priceTextFiled.text=@"0.";
            }
            
            //2个以上字符的处理
            NSRange pointRange = [x rangeOfString:@"."];
            NSRange pointsRange = [x rangeOfString:@".."];
            if (pointsRange.length>0) {
                //含有2个小数点
                priceTextFiled.text=[x substringToIndex:x.length-1];
            }
            else if (pointRange.length>0){
                //含有1个小数点时,并且已经输入了数字,则不能再次输入小数点
                if ((pointRange.location!=x.length-1) && ([[x substringFromIndex:x.length-1]isEqualToString:@"."])) {
                    priceTextFiled.text=[x substringToIndex:x.length-1];
                }
                if (pointRange.location+maxFloatLength<x.length) {
                    //输入位数超出精确度限制,进行截取
                    priceTextFiled.text=[x substringToIndex:pointRange.location+maxFloatLength+1];
                }
            }
            else{
                if (x.length>maxIntegerLength) {
                    priceTextFiled.text=[x substringToIndex:maxIntegerLength];
                }
            }
            
        }
        
    }];

原文地址:https://www.cnblogs.com/ashamp/p/4552707.html