Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone Auto-scroll UITextView but allow manual scrolling also

I have a UITextView that has a lot of content. I have a button that allows the UITextView to automatically scroll + 10 pixels in an NSTimer loop:

scrollPoint = CGPointMake(scrollPoint.x, scrollPoint.y + 10);
[textView setContentOffset:scrollPoint animated:YES];   

This works really well, as the animation makes the scroll rather smooth. I want to allow the user to skip ahead or back by scrolling with their finger, however due to this code after the scroll animation, the scroll snaps back to where it would have auto-scrolled.

I need to reset the scrollPoint variable after a manual scroll, but I'm not sure how to do that. I've tried implementing the delegate method

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView;

but this method fires on my automatic scroll as well.

Any ideas?

like image 861
Ben Scheirman Avatar asked Jul 06 '09 20:07

Ben Scheirman


2 Answers

You could just make it move relative to where it is:

scrollPoint = textView.contentOffset;
scrollPoint.y= scrollPoint.y+10;
[textView setContentOffset:scrollPoint animated:YES];
like image 196
Dan Lorenc Avatar answered Oct 21 '22 11:10

Dan Lorenc


I wanted to do the same thing you are trying to do Ben, but I found that the animation was too costly in terms of display time and seemed to defeat the purpose. I played around with it and found the following code does exactly what you wanted it to do and doesn't bog down the system at all.

Setup

if (autoscrollTimer == nil) {
  autoscrollTimer = [NSTimer scheduledTimerWithTimeInterval:(35.0/1000.0)
                                                     target:self
                                                   selector:@selector(autoscrollTimerFired:) 
                                                   userInfo:nil 
                                                    repeats:YES];
}

The key is in turning the animation OFF and moving the offset in smaller increments. It seems to run faster and it doesn't interfere with the manual scroll.

- (void)autoscrollTimerFired:(NSTimer*)timer {
   CGPoint scrollPoint = self.textView.contentOffset;
   scrollPoint = CGPointMake(scrollPoint.x, scrollPoint.y + 1);
   [self.textView setContentOffset:scrollPoint animated:NO];
}

I am pretty new to objective-c and iphone development so if anybody with more experience sees a problem with this approach I would appreciate any feedback.

like image 43
Primc Avatar answered Oct 21 '22 09:10

Primc