I\'m attempting to setup a scrollview with infinite (horizontal) scrolling.
Scrolling forward is easy - I have implemented scrollViewDidScroll, and when the contentO
When I had faced this problem I had 3 images, which needed to be able to scroll infinitely in either direction. The optimal solution would probably be to load 3 images and modifying the content panel when user moves to rightmost/ leftmost image but I have found an easier solution. (Did some editing on the code, might contain typos)
Instead of 3 images, I have setup a scroll view with 5 images, like:
3 | 1 | 2 | 3 | 1
and calculated the content view accordingly, whereas the content size is fixed. Here is the code:
for ( NSUInteger i = 1; i <= NO_OF_IMAGES_IN_SCROLLVIEW + 2 ; i ++) {
UIImage *image;
if ( i % 3 == 1){
image = [UIImage imageNamed:[NSString stringWithFormat:@"img1.png"]];
}
else if (i % 3 == 2 ) {
image = [UIImage imageNamed:[NSString stringWithFormat:@"img2.png"]];
}
else {
image = [UIImage imageNamed:[NSString stringWithFormat:@"img3.png"]];
}
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake((i-1)*_scrollView.frame.size.width, 0, _scrollView.frame.size.width, _scrollView.frame.size.height)];
imageView.contentMode=UIViewContentModeScaleToFill;
[imageView setImage:image];
imageView.tag=i+1;
[self.scrollView addSubview:imageView];
}
[self.scrollView setContentOffset:CGPointMake(self.scrollView.frame.size.width, 0)];
[scrMain setContentSize:CGSizeMake(self.scrollView.frame.size.width * ( NO_OF_IMAGES_IN_SCROLLVIEW + 2 ), self.scrollView.frame.size.height)];
Now that the images are added, the only thing is to create the illusion of infinite scrolling. To do that I have "teleported" the user into the three main image, whenever he tries to scroll to one of the outer two images. It is important to do that not-animated, so that the user won't be able to feel it:
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
if (scrollView.contentOffset.x < scrollView.frame.size.width ){
[scrollView scrollRectToVisible:CGRectMake(scrollView.contentOffset.x + 3 * scrollView.frame.size.width, 0, scrollView.frame.size.width, scrollView.frame.size.height) animated:NO];
}
}
else if ( scrollView.contentOffset.x > 4 * scrollView.frame.size.width ){
[scrollView scrollRectToVisible:CGRectMake(scrollView.contentOffset.x - 3 * scrollView.frame.size.width, 0, scrollView.frame.size.width, scrollView.frame.size.height) animated:NO];
}
}