为文本字段设置字符数和字符类型限制 swift 4

put character count and character type limit for the textfield swift 4

我想限制文本字段。示例:最大字符数应为 6,字符只能是数字。但我无法将这两个控件放在一个函数中。

文本计数的第一个函数:

func textFieldCharacterCountLimit(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let maxLength = 6
    let currentString: NSString = txt_phone_no_verification_code.text! as NSString
    let newString: NSString =
        currentString.replacingCharacters(in: range, with: string) as NSString
    return newString.length <= maxLength
}

文本类型的第二个函数:

func textFieldCharacterTypeLimit(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let allowedCharacters = CharacterSet.decimalDigits
    let characterSet = CharacterSet(charactersIn: string)
    return allowedCharacters.isSuperset(of: characterSet)
}

除此之外,它还报错。而 textFieldCharacterCountLimit 函数不起作用。我想我得到了一个错误,因为两个函数影响与 return 相同的文本字段。谢谢

您不能只编造委托方法名称。您需要实施正确的方法并在一个方法中完成所有需要的检查。

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let newString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
    if newString.count > 6 {
        return false
    }

    return newString.rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) == nil
}

只允许将一组指定的字符输入到具有特定范围的给定文本字段

   func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if string.count == 0 {
            return true
        }
        let currentText = textField.text ?? ""
        let prospectiveText = (currentText as NSString).replacingCharacters(in: range, with: string)

        return prospectiveText.containsOnlyCharactersIn(matchCharacters: "0123456789") &&
            prospectiveText.count <= 6

    }

带条件的字符串扩展

extension String {

    // Returns true if the string contains only characters found in matchCharacters.
    func containsOnlyCharactersIn(matchCharacters: String) -> Bool {

        let disallowedCharacterSet = NSCharacterSet(charactersIn: matchCharacters).inverted
        return self.rangeOfCharacter(from: disallowedCharacterSet as CharacterSet) == nil
    }
}

How to program an iOS text field that takes only numeric input with a maximum length

http://www.globalnerdy.com/2015/04/27/how-to-program-an-ios-text-field-that-takes-only-numeric-input-or-specific-characters-with-a-maximum-length/