Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITextField starting cursor position is wrong

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)
}

enter image description here

like image 383
Dree Avatar asked May 22 '20 15:05

Dree


1 Answers

You need to always update your UI from the main thread:

DispatchQueue.main.async {
    textField.selectedTextRange = textField.textRange(from: textField.endOfDocument, to: textField.endOfDocument)
}
like image 138
Leo Dabus Avatar answered Nov 20 '22 14:11

Leo Dabus