Hello everyone!) Need some help!)
How can I allow the user to enter only one sentence (word or characters) in a TextField with some rules?)
The user must enter only this word:
Qwerty
Then text field must shows automatically hyphen:
Qwerty-
And after that the user can type in text field only this digits:
12345
Expected result must be only this:
Qwerty-12345
The order of entering each letter or number is very important!)
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let text = onlyCharTextField.text else { return true }
if textField == onlyCharTextField {
let allowedCharacters = "Q-w-e-r-t-y "
let allowedCharacterSet = CharacterSet(charactersIn: allowedCharacters)
let allowedDigits = "1-2-3-4-5"
let allowedDigitSet = CharacterSet(charactersIn: allowedDigits)
if text == "Qwerty" {
onlyCharTextField.text = "Qwerty" + "-"
}
let typedCharacterSet = CharacterSet(charactersIn: string)
let alphabet = allowedCharacterSet.isSuperset(of: typedCharacterSet) || allowedDigitSet.isSuperset(of: typedCharacterSet)
return alphabet
} else {
return false
}
}
I’m confused..(( Do you have any ideas how to implement this?)
Thanks for every answer!)
2
Answers
It’s not that complicated. You can use the "first compute what the new text would be" pattern, and then check if "Qwerty-12345" starts with that text. This is because if the text is entered in the correct order, then the text is always a part (or the entirety) of the beginning of "Qwerty-12345":
A special case is when the text is
Qwerty
. This is when you don’t allow the keyboard to change the text, and instead change it programmatically toQwerty-
.Note that this still allows the user to delete what they have already entered, but only from the end, and enter
Qwerty-12345
from the deleted point. If you want to disallow that, you can check if thereplacementString
parameter is empty, which is indicative of a deletion:This doesn’t disable pasting. If you want that, see How to disable pasting in a TextField in Swift?