Dree
Dree

Reputation: 722

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

Upvotes: 9

Views: 1734

Answers (1)

Leo Dabus
Leo Dabus

Reputation: 236260

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

DispatchQueue.main.async {
    textField.selectedTextRange = textField.textRange(from: textField.endOfDocument, to: textField.endOfDocument)
}

Upvotes: 11

Related Questions