我要实现以下目标:

  • 有一个十进制键盘。这意味着用户将能够输入Double
    价值观。 (无需多说“。”。)
  • 防止将“0”字符作为第一个字符。 (即:应该
    不能是“003”,“01”,“000012”等值。)
  • 将字符数限制为10。
  • 仅允许数字。没有复制粘贴文本值。

  • 我正在使用十进制键盘。下面的代码处理上面的第一和第三项:
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let currentString: NSString = (textField.text ?? "") as NSString
        let newString = currentString.replacingCharacters(in: range, with: string)
        return newString.count <= 10
    }
    

    感谢您的时间。

    最佳答案

    波纹管代码将检查您指定的所有条件

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    
    
        //Prevent "0" characters as the first characters. (i.e.: There should not be values like "003" "01" "000012" etc.)
        if textfield.text?.count == 0 && string == "0" {
    
            return false
        }
    
        //Limit the character count to 10.
        if ((textfield.text!) + string).count > 10 {
    
            return false
        }
    
        //Have a decimal keypad. Which means user will be able to enter Double values. (Needless to say "." will be limited one)
        if (textfield.text?.contains("."))! && string == "." {
    
            return false
        }
    
        //Only allow numbers. No Copy-Paste text values.
        let allowedCharacterSet = CharacterSet.init(charactersIn: "0123456789.")
        let textCharacterSet = CharacterSet.init(charactersIn: textfield.text! + string)
        if !allowedCharacterSet.isSuperset(of: textCharacterSet) {
            return false
        }
        return true
    }
    

    10-08 05:50
    查看更多