将光标设置为成为第一响应者时 UITextField 的末尾
我有一个 UITextField
,其文本对齐设置为右嵌入 UICollectionViewCell
中。如果我点击 UITextField
,光标应该位于文本的末尾。另外,如果我点击文本开头或之前的文本字段。 我尝试在 textFieldDidBeginEditing
委托方法中设置位置:
func textFieldDidBeginEditing(_ textField: UITextField) {
let position = textField.endOfDocument
textField.selectedTextRange = textField.textRange(from: position, to: position)
}
但这不起作用,所以我尝试使用 DispatchQueue.main.async。那行得通。但我知道,这不是最优雅的方式,而且看起来有些东西试图同时设置光标位置。
func textFieldDidBeginEditing(_ textField: UITextField) {
DispatchQueue.main.async {
let position = textField.endOfDocument
textField.selectedTextRange = textField.textRange(from: position, to: position)
}
}
有没有更好的解决方案将光标设置在最后一个位置?
I have a UITextField
with a text alignment set to right embedded in a UICollectionViewCell
. If I tap the UITextField
the cursor should be at the end of the text. Also if I tap the textfield on or before of the beginning of the text.
I tried to set the position in the textFieldDidBeginEditing
delegate method:
func textFieldDidBeginEditing(_ textField: UITextField) {
let position = textField.endOfDocument
textField.selectedTextRange = textField.textRange(from: position, to: position)
}
But this didn't work so I tried it with DispatchQueue.main.async. That works. But I know, that this isn't the most elegant way and it looks like something tries to set the cursor position at the same time.
func textFieldDidBeginEditing(_ textField: UITextField) {
DispatchQueue.main.async {
let position = textField.endOfDocument
textField.selectedTextRange = textField.textRange(from: position, to: position)
}
}
Is there a better solution to set the cursor on the last position?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用 DispatchQueue 会使我的光标在视觉上跳跃,因为存在延迟。我不确定下面的解决方案是否更好,因为它增加了复杂性,但我正在尝试。
Using
DispatchQueue
makes my cursor visually jump, since there's a delay. I'm not sure the solution below is better since it adds complexity, but I'm trying it out.