问题描述
我有一个带有一些预编译文本的文本字段.文本字段内的文本在视觉上是右对齐的.当我点击文本字段时,我希望光标位于文本的末尾,以便我可以准备编辑文本.默认情况下,光标位于文本的开头,如果我点击该单词,则位于该单词的末尾.
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.
我尝试按照其他答案的建议设置 selectedTextRange
属性,但我无法实现结果.我注意到 becomeFirstResponder()
给出了正确的行为.
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)
}
推荐答案
您需要始终从主线程更新您的 UI:
You need to always update your UI from the main thread:
DispatchQueue.main.async {
textField.selectedTextRange = textField.textRange(from: textField.endOfDocument, to: textField.endOfDocument)
}
这篇关于UITextField 起始光标位置错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!