1

I have made scrollview for the few collection of images and I want it to autoscroll the images one by one by the interval of 2 sec. By the below code I could able to make all images slide at a time, but I want one image to scroll then other with respect to time.

-(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];
    }
halfer
  • 19,824
  • 17
  • 99
  • 186
taj
  • 23
  • 1
  • 6

1 Answers1

0

Try simple recursion with dispatch_after function. Something like this:

-(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];
    });
}

Please be aware that with this case images will be scrolled even when viewcontroller will disappear. Recursion will end only after closing viewcontroller. If you don't want such behavior you can add extra condition for checking if viewcontroller is visible before dispatching next scroll - you can check how to do his here: How to tell if UIViewController's view is visible

Community
  • 1
  • 1
Łukasz Duda
  • 169
  • 1
  • 4