Making uitextview scroll programmatically

前端 未结 2 1980
青春惊慌失措
青春惊慌失措 2020-12-19 09:50

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.

相关标签:
2条回答
  • 2020-12-19 10:10

    .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....

    0 讨论(0)
  • 2020-12-19 10:18

    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.

    0 讨论(0)
提交回复
热议问题