Swift:限制输入框只能输入带两位小数的数字

       let futureString: NSMutableString = NSMutableString(string: textField.text!)
        futureString.insert(string, at: range.location)
        
        var flag = 0;
        
        let limited = 2;//小数点后需要限制的个数
        
        if !futureString.isEqual(to: "") {
            for i in stride(from: (futureString.length - 1), through: 0, by: -1) {
                let char = Character(UnicodeScalar(futureString.character(at: i))!)
                if char == "." {
                    if flag > limited {
                        return false
                    }
                    break
                }
                flag += 1
            }
        }
        return true

这个很优秀

你可能感兴趣的:(Swift:限制输入框只能输入带两位小数的数字)