iOS——处理无法在 UITextField 中设置光标位置的问题

发布于 2024-10-10 10:43:48 字数 340 浏览 0 评论 0原文

我正在开发一个使用自定义键盘进行文本输入的应用程序。键盘应该有“前进”和“后退”键。

一些对 SO 的搜索表明不可能以编程方式在 UITextField 中设置光标位置。

我考虑过使用 UITextView 来代替。这确实允许设置光标位置。但滚动行为变得非常烦人。

我想知道是否有人知道一个好的解决方法。基本上,我想要有文本和光标的东西,并且我可以以编程方式设置光标位置。

编辑:有趣的是,如果我在模拟器中有一个 UITextField 并且按下 mac 键盘上的前进或后退箭头键,光标确实会向前或向后移动。但是,我看不到任何方法可以在设备上模仿这种行为。 。 。或者,就此而言,用鼠标单击模拟器屏幕。

I am working on an app that will use a custom keyboard for text entry. The keyboard should have "forward" and "back" keys.

Some hunting on SO suggests it is impossible to programmatically set the cursor position in a UITextField.

I've looked at using a UITextView instead. This does allow one to set the cursor position. But the scrolling behavior gets extremely annoying.

I am wondering if anyone is aware of a good workaround. Basically, I want something that has text and a cursor, and I can programmatically set the cursor position.

EDIT: Intriguingly, if I have a UITextField in the simulator and I press the forward or back arrow key on my mac keyboard, the cursor does move forwards or backwards. However, I can't see any way to mimic this behavior on a device . . . or, for that matter, with a mouse click on the simulator screen.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

挽手叙旧 2024-10-17 10:43:48

接受的答案当时是正确的,但现在已经过时了。在iOS 5中,UITextField符合UITextInput协议。因此,可以通过 selectedTextRange 属性设置光标位置。

The accepted answer was correct at the time but is now out of date. In iOS 5, UITextField conforms to the UITextInput protocol. The cursor position can therefore be set via the selectedTextRange property.

小草泠泠 2024-10-17 10:43:48

我还使用 UITextView 来设置光标位置。

如果您子类化 UITextView (它本身是 UIScrollView 的特化),您可以覆盖“scrollingEnabled”并返回 NO:

- (BOOL) scrollingEnabled   
{
    return NO;
}

我还必须使用 contentInset 和 contentOffset 属性才能准确获得我想要的内容。

I also use a UITextView for the very purpose of being able to set the cursor position.

If you subclass UITextView (which itself is a specialization of UIScrollView), you can override "scrollingEnabled" and return NO:

- (BOOL) scrollingEnabled   
{
    return NO;
}

I also had to play with the contentInset and contentOffset properties to get exactly what I wanted.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文