UITextField仅允许使用字母和空格并限制最大字符

时间:2018-12-15 19:19:32

标签: ios swift uitextfield

在文本字段中,我只允许字母和空格。以下解决方案似乎可行,但有几个问题

1)不允许有空格

2)输入时对数字进行计数,并计入不正确的最大限制总数中。我们应该只计算我们在现场看到的东西

我一直在寻找解决方案,但是其中大多数似乎已经过时或不适合该目的。 有帮助吗?

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    // Don't allow number in name field
    if textField == nameTextField && string.count > 0 {
        let textString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
        let LettersOnly = NSCharacterSet.letters
        let strValid = LettersOnly.contains(UnicodeScalar.init(string)!)
        return strValid && textString.count <= 30
    }

    return true
}

1 个答案:

答案 0 :(得分:0)

如果我对您的理解正确,则可以使用以下内容:

class ViewController: UIViewController, UITextFieldDelegate {

    let allowedCharacters = CharacterSet.letters.union(CharacterSet(charactersIn: " "))
    let maxLength = 10

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let newText = (textField.text! as NSString).replacingCharacters(in: range, with: string)

        // check characters
        guard newText.rangeOfCharacter(from: allowedCharacters.inverted) == nil else { return false }

        // check length
        guard newText.count <= maxLength else { return false }

        return true
    }

}

或更短:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let newText = (textField.text! as NSString).replacingCharacters(in: range, with: string)
    return (newText.rangeOfCharacter(from: allowedCharacters.inverted) == nil) && (newText.count <= maxLength)
}