0

在下面的 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
}
4

3 回答 3

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()然后返回trueorfalse

编辑:替代使用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
}

如果guard不满足语句(word.characters.count < 3),函数会自动返回false

于 2017-09-12T14:36:18.043 回答
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
    }
}
于 2017-09-12T14:39:18.020 回答
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_YourViewController

yourTextField.delegate = self
于 2017-09-12T14:42:06.187 回答