2
votes

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.

2

2 Answers

4
votes

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.

0
votes

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.