美文网首页
iOS开发笔记-125:swift5 UITextField输

iOS开发笔记-125:swift5 UITextField输

作者: 原味蛋炒饭 | 来源:发表于2022-09-09 15:59 被阅读0次

    设置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输

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