Search code examples
iphoneioscursoruitextfieldcursor-position

iOS -- dealing with the inability to set the cursor position in a UITextField


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.


Solution

  • 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.