Swift UITextField 限制输入:小数点后俩位,总值

2020-06-17  本文已影响0人  Persistent丧心病狂
 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        // 限制小数点后俩位
        var futureString: String = textField.text ?? ""
        if string == "" {
            return true
        }
        if !matchCharacter(c: string) {
            return false
        }
        futureString.insert(Character(string), at: futureString.index(futureString.startIndex, offsetBy: range.location))
        
        // 设置欠款金额最大值
        if futureString.DoubleValue >= 100000000 {
            return false
        }
        var flag: Int = 0
        var array: [Character] = [Character]()
        
        for c in futureString {
            array.append(c)
        }

        if string == "." {
            // 如果插入小数点,要判断当前光标的位置和字符串的长度
            if futureString.count - range.location > 3 {
                return false
            }
        }
        
        for  c in array.reversed() {
            if c == "." {
                
                if isEqual(arr: array) {
                   return false
                }
                
                if flag > limited {
                    if range.location == futureString.count - 1 || range.location == futureString.count - 2 || range.location == futureString.count - 3{
                        return false
                    } else {
                        return true
                    }
                }
            }
            flag += 1;
        }
        return true
    }
    
    /// 判断数组中是否有俩个小数点
    func isEqual(arr: [Character]) -> Bool {
        var flag: Int = 0
        
        for c in arr {
            if c == "." {
                flag += 1
                if flag >= 2 {
                    return true
                }
            }
        }
        return false
    }
    
    // 正则匹配数字和小数点
    func matchCharacter(c: String) -> Bool {
       let reg = "^[0-9.]+$"
       let pre = NSPredicate(format: "SELF MATCHES %@", reg)
       if pre.evaluate(with: c) {
           return true
       }else{
           return false
        }
    }
上一篇下一篇

猜你喜欢

热点阅读