如何使用 Swift 防止“0”作为第一个字符并限制 UITextField 中允许的字符数?

How to prevent "0" as the first character and limit number of characters allowed in UITextField using Swift?

我想实现以下目标:

  1. 有一个小数点键盘。这意味着用户将能够输入 Double 值。 (不用说"."就限一个)
  2. 防止“0”字符作为第一个字符。 (即:应该 不是像“003”“01”“000012”等值)
  3. 将字符数限制为 10。
  4. 只允许数字。没有复制粘贴文本值。

我正在使用十进制键盘。下面的代码处理上面的第一项和第三项:

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
}

感谢您的宝贵时间。

您可以创建此方法来防止复制粘贴

override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool {
        if action == "paste:" {
            return false
        }        
        return super.canPerformAction(action, withSender: sender)
    }

您还可以将以下代码添加到 shouldChangeCharactersInRange 文本字段的委托方法

  let searchString = (txtMobilePhone.text as NSString?)?.replacingCharacters(in: range, with: string)

        if (searchString?.length)! > 1 {

            let inverseSet = CharacterSet(charactersIn: ".0123456789").inverted

            return ((string as NSString).rangeOfCharacter(from: inverseSet).location == NSNotFound)

        } else {

            let inverseSet = CharacterSet(charactersIn: ".123456789").inverted

            return ((string as NSString).rangeOfCharacter(from: inverseSet).location == NSNotFound)
        }

以上仅允许用户在第二个字符后输入“0”我的意思是限制用户在数字开头输入“0”

下面的代码将检查您指定的所有条件

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 位且不以 0 开头的数字,然后使用 NSPredicate 或 NSRegularExpression 来验证输入的文本。像这样:

func isAllowed(str: String?) -> Bool {
    let regexPattern: String = "^((?!(0))[0-9]{0,10})$"
    let predicate = NSPredicate(format:"SELF MATCHES %@", regexPattern)

    return predicate.evaluate(with: str)
}

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    return isAllowed(str: textField.text)
}