In the Swift code below, the user chooses a word and types it into a text box, now how to disallow the words entered if less than 3 characters in length?
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
}
You can just add an if
to check if the word has more than 3 characters:
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
}
}
This way, if word
is shorter than 3 characters, it will return false
, otherwise, it will test against the UITextChecker()
and then return true
or false
respectively
EDIT: Alternative using 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
}
If the guard
statement is not met (being word.characters.count < 3), the function will automatically return false
You can implement the didEndEditing UItextfieldDelegate method and then check 1) that its a single word and 2) that its longer than 2 characters. At that point you then need to show an error or a red caption label or something.
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
}
}
You don't need to implement new functions to check an input coming from a UITextField
. UITextField
has its own functions for that. You should make your ViewController class conform to the UITextFieldDelegate
protocol, set it as the delegate for your UITextField
, then implement the required delegate method, textFieldDidEndEditing
and check the length of the input there.
extension YourViewController: UITextFieldDelegate {
func textFieldDidEndEditing(_ textField: UITextField) {
guard let input = textField.text else {return}
if input.characters.count < 3 {
//handle error
}
}
}
In viewDidLoad
of YourViewController
:
yourTextField.delegate = self
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.