Setting UITextView cursor position to end of text
I was trying to make a currency field. I did not want the user pressing all over the field and potentially deleting formatted text. The easiest way I found to keep the cursor at the end is to do the following in a subclass of UITextField
-(void) setSelectedTextRange:(UITextRange *)selectedTextRange{
[super setSelectedTextRange:selectedTextRange];
self.text = self.text;
}
To move the cursor to the end
textView.selectedRange = NSMakeRange([textView.text length], 0);
or to move the cursor to after the third character
textView.selectedRange = NSMakeRange(3, 0);
Another, maybe better, approach might be to clear the first three characters out when the user starts editing, then add them back in once editing is over.
You could consider registering to the UIKeyboardWillShowNotification
and upon receiving the notification, set the textview's userInteractionEnabled
to NO
.
Also, implement the shouldChangeTextInRange
method in a way that if replacementText
is equal to the string @""
you don't change the text (@""
meaning the user is tapping backspace). Restore user interaction when the user finishes editing the text and there you go.
Good luck!
It's late but i found working solution for this in some blog . it needs a little hack
- (void) textViewDidBeginEditing:(UITextView*)textview
{
[self performSelector:@selector(placeCursorAtEnd:) withObject:textview afterDelay:0.01];
}
- (void)placeCursorAtEnd:(UITextView *)textview
{
NSUInteger length = textview.text.length;
textview.selectedRange = NSMakeRange(length, 0);
}