Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making uitextview scroll programmatically

I want to make my uitextview to scroll automatically whenever the application is launched. Can anyone help me with a detailed code? I am new to iPhone SDK.

like image 810
user919050 Avatar asked Sep 01 '11 06:09

user919050


2 Answers

.h file

@interface Credits : UIViewController 
{
    NSTimer *scrollingTimer;

    IBOutlet UITextView *textView;


}
@property (nonatomic , retain) IBOutlet UITextView *textView;

- (IBAction) buttonClicked ;

- (void) autoscrollTimerFired;

@end

.m file

- (void) viewDidLoad
{       
    // it prints the initial position of text view 
    NSLog(@"%f %f",textView.contentSize.width , textView.contentSize.height);

    if (scrollingTimer == nil)
    {
        // A timer that updates the content off set after some time so it can scroll 
        // you can change time interval according to your need (0.06)
        // autoscrollTimerFired is the method that will be called after specified time interval. This method will change the content off set of text view
        scrollingTimer = [NSTimer scheduledTimerWithTimeInterval:(0.06)
                         target:self selector:@selector(autoscrollTimerFired) userInfo:nil repeats:YES];        
    }
}

- (void) autoscrollTimerFired
{
    CGPoint scrollPoint = self.textView.contentOffset; // initial and after update
    NSLog(@"%.2f %.2f",scrollPoint.x,scrollPoint.y);
    if (scrollPoint.y == 583) // to stop at specific position 
    {
        [scrollingTimer invalidate];
        scrollingTimer = nil;
    }
    scrollPoint = CGPointMake(scrollPoint.x, scrollPoint.y + 1); // makes scroll
    [self.textView setContentOffset:scrollPoint animated:NO];
    NSLog(@"%f %f",textView.contentSize.width , textView.contentSize.height);

}

Hope it helps you....

like image 131
Maulik Avatar answered Sep 28 '22 02:09

Maulik


UITextView derives from UIScrollview so you can set the scrolling position using -setContentOffset:animated:.

Assuming you want to scroll smoothly at the speed of 10 points per second, you'd do something like that.

- (void) scrollStepAnimated:(NSTimer *)timer {
    CGFloat scrollingSpeed = 10.0; // 10 points per second
    NSTimeInterval repeatInterval = [timer timeInterval]; // ideally, something like 1/30 or 1/10 for a smooth animation

    CGPoint newContentOffset = CGPointMake(self.textView.contentOffset.x, self.textView.contentOffset.y + scrollingSpeed * repeatInterval);
    [self.textView setContentOffset:newContentOffset animated:YES];
}

Of course you have to setup the timer and be sure to cancel the scrolling when the view disappears and so on.

like image 35
Fabian Kreiser Avatar answered Sep 28 '22 04:09

Fabian Kreiser