iOS开发笔记-125:swift5 UITextField输入限制,小数点后2位

设置UITextFieldDelegate
keyboardType = .decimalPad

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        let text = textField.text ?? ""
        
        if text == "0." && string.count == 0 {
            textField.text = ""
            return false
        }
        
        let toBeString = (text as NSString).replacingCharacters(in: range, with: string)
        
        if string == "." && text.count == 0 {
            textField.text = "0."
            return false
        }
        
        if string == "." && text.contains(".") {
            return false
        }
        
        if text.contains(".") && toBeString.components(separatedBy: ".").count > 1 && toBeString.components(separatedBy: ".").last?.count ?? 0 > 2 {
            return false
        }
        return true
    }

你可能感兴趣的:(iOS开发笔记-125:swift5 UITextField输入限制,小数点后2位)