I have a textfield with some precompiled text. Text inside the textfield is visually right aligned. When I tap on the textfield I would like the cursor to be at the end of the text, so I can be ready to edit the text. By default the cursor is positioned at the start of the text or at the end of a word if I tap that word.
I tried to set the selectedTextRange
property as suggested by other answers but I cannot manage to achieve the result. I noticed by the way that becomeFirstResponder()
gives the correct behavior.
func textFieldDidBeginEditing(_ textField: UITextField) {
textField.selectedTextRange =
textField.textRange(from: textField.endOfDocument, to: textField.endOfDocument)
}
You need to always update your UI from the main thread:
DispatchQueue.main.async {
textField.selectedTextRange = textField.textRange(from: textField.endOfDocument, to: textField.endOfDocument)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With