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!)
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":
Q
Qw
Qwe
Qwer
Qwert
Qwerty-
Qwerty-1
Qwerty-12
Qwerty-123
Qwerty-1234
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 to Qwerty-
.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let text = (textField.text ?? "") as NSString
let newText = text.replacingCharacters(in: range, with: string)
if newText == "Qwerty" {
textField.text = "Qwerty-"
return false
}
return "Qwerty-12345".starts(with: newText)
}
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 the replacementString
parameter is empty, which is indicative of a deletion:
if string.isEmpty {
return false
}
This doesn't disable pasting. If you want that, see How to disable pasting in a TextField in Swift?