MahdiS MahdiS -4 years ago 155
Objective-C Question

Prevent user from setting cursor position on UITextField

I have an UITextField constructed using the storyboard. I want to not allow the user to change the position of the cursor and keep it always at the end of the text into the text field.

I tried to change the position of the cursor at the touch down event, but when selecting the text field and then change the position of cursor by touching the text field again, the position is changed:

- (IBAction)amountBoxTouchDown:(id)sender {
UITextPosition *start = [amountBox positionFromPosition:[amountBox beginningOfDocument] offset:amountBox.text.length];
UITextPosition *end = [amountBox positionFromPosition:start
offset:0];
[amountBox setSelectedTextRange:[amountBox textRangeFromPosition:start toPosition:end]];
}


Does any one know a solution? Thanks

Answer Source

Ok, what you have to do is have a UITextField that is hidden.

Add that hidden text field to the view, and call becomeFirstResponder on it. From your amountBoxTouchDown: method.

In the Textfield delegate, take the text the user typed in and add it to amountBox.text. Also turn off userInteractionEnabled for the visible amountBox textField.

This creates the effect you desire.

Have a look at for some sample code Link.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download