美文网首页
Swift UITextField 限制输入:小数点后俩位,总值

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

作者: Persistent丧心病狂 | 来源:发表于2020-06-17 17:37 被阅读0次
     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
            }
        }
    

    相关文章

      网友评论

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

          本文链接:https://www.haomeiwen.com/subject/wsgsxktx.html