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

时间:2017-11-13 12:50:18

标签: ios swift uitextfield uikeyboard

我想实现以下目标:

  1. 有一个小数键盘。这意味着用户可以输入Double 值。 (不用说“。”将受到限制)
  2. 防止“0”字符作为第一个字符。 (即:应该 不是像“003”“01”“000012”等的值。)
  3. 将字符数限制为10。
  4. 仅允许数字。没有复制粘贴文本值。
  5. 我正在使用小数键盘。下面的代码处理上面的第一项和第三项:

    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
    }
    

    感谢您的时间。

3 个答案:

答案 0 :(得分:4)

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

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
}

答案 1 :(得分:0)

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

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

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

让searchString =(txtMobilePhone.text为NSString?)?. replacementCharacters(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)
        }

以上这个只允许用户输入&#34; 0&#34;在第二个字符后,我的意思是限制用户键入&#34; 0&#34;在数字的开头

答案 2 :(得分:0)

您可以使用正则表达式定义一个数字,其中&lt; = 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)
}