n.evermind
n.evermind

Reputation: 12004

scrollRangeToVisible: How to scroll to the beginning of an UITextView

A beginner's headache: I am trying to scroll to the very top of my UITextView once the keyboard is dismissed. I had tried to extract an answer from here, but I'm afraid it didn't help much.

I thought I do this with scrollRectToVisible, but nothing happens. Then I thought I should try scrollRangeToVisible, but this crashed my app... I'm sure I've done something tremendously upsetting and wrong. I'd be very glad if somebody could help:

- (IBAction)hideKeyboard:(id)sender {

//[textView scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:YES];

NSRange range = NSMakeRange(textView.text.length - (textView.text.length+1),1);
[textView scrollRangeToVisible:range];

textView.scrollEnabled = NO;
[textView resignFirstResponder];}

EDIT:

updated code for anyone who encounters a similar problem:

- (IBAction)hideKeyboard:(id)sender {

//textView.scrollEnabled = NO;
[textView resignFirstResponder];

NSRange range = NSMakeRange(0,1);
[textView scrollRangeToVisible:range];

}

Upvotes: 3

Views: 10345

Answers (2)

Mejdi Lassidi
Mejdi Lassidi

Reputation: 999

i found this answer ,about scrolling textView to top, before here in this forum ,i did'nt find it now .But this was the answer: You just use this method to stop scroll:

- (void)killScroll :(UIScrollView*)scrollView 
{
    CGPoint offset = scrollView.contentOffset;
    offset.x -= 1.0;
    offset.y -= 1.0;
    [scrollView setContentOffset:offset animated:NO];
    offset.x += 1.0;
    offset.y += 1.0;
    [scrollView setContentOffset:offset animated:NO];
}

and after calling it ,you use the famous method:

[yourTextView scrollsToTop];

Upvotes: -1

James Bedford
James Bedford

Reputation: 28962

The range you're creating starts at -1! You can create your range as follows, it's easier:

NSRange range = NSMakeRange(0, 1);

This range starts at an index of 0 (first character) and spreads over 1 characters.

Upvotes: 5

Related Questions