gpt4 book ai didi

ios - 设置 UITextField 的光标位置不起作用(快速)

转载 作者:行者123 更新时间:2023-11-28 08:25:35 28 4
gpt4 key购买 nike

我浏览了这篇文章 Getting and Setting Cursor Position of UITextField and UITextView in Swift我遇到了选择文本的问题。

我按照引用帖子中的示例进行操作,但仍然看不到任何结果。我创建了一个基本的 SingleViewApplication,其中只有一个 UITextField。

Textfield 在 vi​​ewDidLoad 中设置为“foobar”

    override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
textField.text = "foobar" }

在@IBAction Editing Did Begin 我尝试使用这篇文章中描述的方法选择整个文本,见下文。

@IBAction func EDB(_ sender: UITextField) {
let startPosition = textField.beginningOfDocument
let endPosition = textField.endOfDocument
textField.selectedTextRange = textField.textRange(from: startPosition, to: endPosition )
}

我希望将选择我的 textField 中的所有文本。

它没有。

我放了两个断点来显示我的textField的选定范围在线让开始位置....最后一行那些断点执行 po textField.selectedTextRange!并继续。

它确认我有效地更改了我的 textField 的范围

<_UITextKitTextRange: 0x7fa42bb0d140> (6, 0)F

<_UITextKitTextRange: 0x7fa42b922640> (0, 6)F

但是在 UI 上没有可见的选择并且光标停留在我的文本字段的末尾。

要让 UI 显示我选择的范围,我缺少什么?

基本上,当用户输入版本时,我想预先选择我的 UItextField 的特定范围的文本。

最佳答案

尝试将选择范围包装到另一个方法中并延迟调用它。我不完全了解你的情况,但在少数情况下,小延迟对我有帮助。

这是 Swift 2 版本:

@IBAction func EDB(sender: UITextField) {
performSelector(#selector(selectRange), withObject: nil, afterDelay: 0.01)
}

@objc private func selectRange() {
let startPosition = textField.beginningOfDocument
let endPosition = textField.endOfDocument
textField.selectedTextRange = textField.textRange(from: startPosition, to: endPosition)
}

关于ios - 设置 UITextField 的光标位置不起作用(快速),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40124164/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com