如何使用计时器自动滚动UIScrollView

var*_*mab 18 iphone uiscrollview

我有scrollview来显示图像.我需要计时器每5秒一个接一个地显示图像.如何使用计时器启动UIScrollView事件以在5秒后移动?

Abr*_*odj 30

将变量int h添加到接口,将yourScrollView作为属性添加.然后:

[NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(onTimer) userInfo:nil repeats:YES];

- (void) onTimer {

    // Updates the variable h, adding 100 (put your own value here!)
    h += 100; 

    //This makes the scrollView scroll to the desired position  
    yourScrollView.contentOffset = CGPointMake(0, h);  

}
Run Code Online (Sandbox Code Playgroud)

  • 要平滑地为滚动设置动画,请使用以下方法:`[yourScrollView setContentOffset:CGPointMake(0,h)animated:YES];` (7认同)

iSa*_*007 10

修改上面的代码

 [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(onTimer)   userInfo:nil repeats:YES];

-(void) onTimer {
  // NSLog(@"content offset %f",scrollVw.contentOffset.y);
  if (scrollVw.contentOffset.y<MAX_ALLOWED_OFFSET) {
   //scroll to desire position
    scrollVw.contentOffset = CGPointMake(0, scrollVw.contentOffset.y+1);
  }


  }
Run Code Online (Sandbox Code Playgroud)