禁止少于3个字符的单词

时间:2017-09-12 14:27:14

标签: ios swift uitextchecker

在下面的Swift代码中,用户选择一个单词并将其输入到文本框中, 现在如果长度少于3个字符,如何禁止输入的单词?

func isReal (word: String) -> Bool {
    //return true
    let checker = UITextChecker()
    let range = NSMakeRange(0, word.utf16.count)
    let misspelledRange = checker.rangeOfMisspelledWord(in: word, range: range, startingAt: 0, wrap: false, language: "en")
    return misspelledRange.location == NSNotFound
}

3 个答案:

答案 0 :(得分:1)

您只需添加if即可检查该字词是否超过3个字符:

func isReal (word: String) -> Bool {
    if word.characters.count >= 3 {
        //return true
        let checker = UITextChecker()
        let range = NSMakeRange(0, word.utf16.count)
        let misspelledRange = checker.rangeOfMisspelledWord(in: word, range: range, startingAt: 0, wrap: false, language: "en")
        return misspelledRange.location == NSNotFound
    } else {
        return false
    }
}

这样,如果word短于3个字符,它将返回false,否则,它将针对UITextChecker()进行测试,然后返回true或{{ 1}}分别

编辑:替代使用false

guard

如果不满足func isReal (word: String) -> Bool { guard word.characters.count >= 3 else { return false } //return true let checker = UITextChecker() let range = NSMakeRange(0, word.utf16.count) let misspelledRange = checker.rangeOfMisspelledWord(in: word, range: range, startingAt: 0, wrap: false, language: "en") return misspelledRange.location == NSNotFound } 语句(为word.characters.count< 3),该函数将自动返回guard

答案 1 :(得分:1)

您可以实现didEndEditing UItextfieldDelegate方法,然后检查1)它是一个单词,2)它是否超过2个字符。此时,您需要显示错误或红色标题标签等。

func textFieldDidEndEditing(_ textField: UITextField, reason: UITextFieldDidEndEditingReason) {
    guard let string = textField.text else {
        return
    }
    let characterSet = CharacterSet(charactersIn: string)
    if characterSet.intersection(CharacterSet.whitespacesAndNewlines).isEmpty != true {
        // we have white space!
    }
    if string.characters.count < 3 {
        // too short
    }
}

答案 2 :(得分:0)

您不需要实现新功能来检查来自UITextField的输入。 UITextField有自己的功能。您应该使ViewController类符合UITextFieldDelegate协议,将其设置为UITextField的委托,然后实现所需的委托方法textFieldDidEndEditing并检查输入的长度。

extension YourViewController: UITextFieldDelegate {
    func textFieldDidEndEditing(_ textField: UITextField) {
        guard let input = textField.text else {return}
        if input.characters.count < 3 {
            //handle error
        }
    }
}

viewDidLoad的{​​{1}}:

YourViewController