问题描述
我正在开发一个应用程式,会使用自订键盘进行文字输入。键盘应该有向前和后退键。
I am working on an app that will use a custom keyboard for text entry. The keyboard should have "forward" and "back" keys.
在SO上的一些寻找表明不可能通过编程方式在UITextField中设置光标位置。
Some hunting on SO suggests it is impossible to programmatically set the cursor position in a UITextField.
我已经看过使用UITextView。这允许设置光标位置。但是滚动行为变得非常烦人。
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.
编辑:有趣的是,如果我有一个UITextField在模拟器和按下Mac键盘上的向前或向后箭头键,光标将向前或向后移动。但是,我看不到在设备上模仿这种行为的任何方式。 。 。
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.
推荐答案
我也使用一个UITextView的目的
I also use a UITextView for the very purpose of being able to set the cursor position.
如果你的子类UITextView(它本身是UIScrollView的一个特殊化),你可以重写scrollingEnabled并返回NO:
If you subclass UITextView (which itself is a specialization of UIScrollView), you can override "scrollingEnabled" and return NO:
- (BOOL) scrollingEnabled
{
return NO;
}
我还必须使用contentInset和contentOffset属性来获得
I also had to play with the contentInset and contentOffset properties to get exactly what I wanted.
这篇关于iOS - 处理无法在UITextField中设置光标位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!