Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Position cursor to end of text in uitextview and scroll to position

Using the code below, I put text from a plist into a textView. The textView is not yet firstresponder; the text is initially for reading only. In iOS4 the goToEndOfNote code positions the cursor at the end of the text AND scrolls to that position. In 3.1.3 it doesn't scroll to the end until the screen is touched (which isn't required unless a change or addition is required), making the textView firstresponder. I would like it to work in 3.1.3 as it does in 4.0. Any ideas please. Thanks.

    ...
    self.temp = [[[NSMutableArray alloc] initWithContentsOfFile:myPlistPath] autorelease]; 
    self.textView.text = [self.temp objectAtIndex:0];
    [self goToEndOfNote];
    //[self performSelector:@selector(goToEndOfNote) withObject:nil afterDelay:0.1];
}

- (void) goToEndOfNote {
    NSUInteger length = self.textView.text.length;  
    self.textView.selectedRange = NSMakeRange(length, 0);
}
like image 296
Matt Winters Avatar asked Sep 07 '10 17:09

Matt Winters


2 Answers

I use setContentOffset:animated to scroll to the top of a UITextView in one of my apps. Should work for scrolling to the bottom, too. Try:

- (void) goToEndOfNote {
    NSUInteger length = self.textView.text.length;  
    self.textView.selectedRange = NSMakeRange(length, 0);
    [textView setContentOffset:CGPointMake(0, length) animated:YES];
}

You could also wrap that up so it only happens for 3.1.3 and below:

- (void) goToEndOfNote {
    NSUInteger length = self.textView.text.length;  
    self.textView.selectedRange = NSMakeRange(length, 0);
    NSString* systemVersion = [[UIDevice currentDevice] systemVersion];
    float version = [systemVersion floatValue];
    if (version < 3.2) {
        [textView setContentOffset:CGPointMake(0, length) animated:YES];
    }
}
like image 52
Shaggy Frog Avatar answered Sep 27 '22 21:09

Shaggy Frog


Not sure if this is THE answer but it works.

In 3.1.3, with the original code, the cursor was at the end but the scroll was at the top. In 4.0, both were at the bottom.

NSUInteger length = self.textView.text.length;
self.textView.selectedRange = NSMakeRange(length, 0);

I then noticed that in 3.1.3, switching the 0 and the length, the scroll was at the bottom but the cursor was at the top.

NSUInteger length = self.textView.text.length;
self.textView.selectedRange = NSMakeRange(0, length); 

Putting the two together worked. It scrolls to the bottom NSMakeRange(0, length) presumably to the end of the range, then the NSMakeRange(length, 0) puts the cursor there, all with no change to what it does in 4.0

NSUInteger length = self.textView.text.length;
self.textView.selectedRange = NSMakeRange(0, length); 
self.textView.selectedRange = NSMakeRange(length, 0);
like image 41
Matt Winters Avatar answered Sep 27 '22 22:09

Matt Winters