2017-02-04 7 views
1

私は、画像のいくつかのコレクションのためにscrollviewをしたと私はそれが2秒の間隔により1の画像を1つずつ自動スクロールします。以下のコードでは、一度にすべての画像をスライドさせることができましたが、1つの画像をスクロールしてから別の画像にスクロールさせます。Objective Cを使用して、2秒間隔でイメージを1つずつ自動スクロールする方法は?

-(void)scrollPages{ 

UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0,0, self.view.frame.size.width, self.view.frame.size.height)]; 
scrollView.contentSize = CGSizeMake(320, 465); 

[scrollView setScrollEnabled:YES]; 
[scrollView setPagingEnabled:YES]; 
[scrollView setAlwaysBounceVertical:NO]; 
[self.uiSubView addSubview:scrollView]; 

NSMutableArray *arrImage = [NSMutableArray arrayWithObjects:@"a.jpeg", @"cat.jpg", @"s.jpeg",@"ss.jpeg", nil]; 

for (int i = 0; i < [arrImage count]; i++) 
{ 
    CGFloat xOrigin = i * scrollView.frame.size.width; 


    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(xOrigin, 0, scrollView.frame.size.width, scrollView.frame.size.height)]; 
    [imageView setImage:[UIImage imageNamed:[arrImage objectAtIndex:i]]]; 
    [imageView setContentMode: UIViewContentModeScaleAspectFit]; 

    [scrollView addSubview:imageView]; 


} 

[scrollView setContentSize:CGSizeMake(scrollView.frame.size.width * [arrImage count], scrollView.frame.size.height)]; 



CGFloat currentOffset = scrollView.contentOffset.x; 

if(currentOffset < 2500){ 

    CGFloat newOffset = currentOffset + 1250; 



    [UIScrollView beginAnimations:nil context:NULL]; 
    [UIScrollView setAnimationDuration:3]; 
    [scrollView setContentOffset:CGPointMake(newOffset,0.0) animated:YES]; 
    } 

答えて

0

dispatch_after関数を使用して単純な再帰を試行してください。このような 何か:この場合に画像がのViewControllerが消えても、スクロールされることに注意して

-(void)scrollToNextImage{ 
    //place here code for computing and setting scrollview offset 

    _weak typeof(self) weakSelf = self; //for avoiding retain cycle 
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ 
     [weakSelf scrollToNextImage]; 
    }); 
} 

してください。再帰はviewcontrollerを終了した後で終了します。あなたがそのような行動をしたくない場合のViewControllerは、次のスクロールをディスパッチする前に表示されている場合は、チェックのための余分な条件を追加することができます - あなたは彼のここを行う方法を確認することができます:How to tell if UIViewController's view is visible

関連する問題