Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting UITextView cursor position to end of text

Tags:

ios

uitextview

I've looked for a solution to this all morning, but have yet to find something that works.

I have a text view that has some existing fixed text in it that I don't want the user to be able to modify. In this case, each of my text views start with "1. ", "2. ", etc. The idea being that the text they entered will be numbered for something I'm doing later.

I don't want the user to be able to delete this text (it is essentially "permanent"). I also don't want to allow them to start adding text in the middle of this pre-text.

To handle this, I have done:

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text 
{
    if (range.location < 3) return NO;

    return YES;
}

This works great, except that if the user touches anywhere in my "1. ", "2. ", etc. parts of the view, it will set the cursor there, which then prevents the user from typing text because of the range location check. What I want to do in this case is set the cursor (perhaps in textViewDidBeginEditing) to the end of the text in the view. However, regardless of what combination of selectedRange I use, I just can't get the darn cursor to move to the end. Any help would be greatly appreciated.

like image 476
Jason Avatar asked May 25 '12 15:05

Jason


1 Answers

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.

like image 198
trapper Avatar answered Mar 07 '23 16:03

trapper