Infinite horizontal scrolling UIScrollView

2019-02-07 08:33发布

I have a UIScrollView whose content size is 1200x480. I have some image views on it, whose width adds up to 600. When scrolling towards the right, I simply increase the content size and set the offset so as to make everything smooth (I then want to add other images, but that's not important right now). So basically, the images currently in the viewport remain somewhere on the left, eventually to be removed from the superview.

Now, the problem that I have happens when scrolling towards the left. What I do is I move the images to the end of the content size (so add 600 to each image view's origin.x), and then set the content offset accordingly. It works when the finger is on the screen and the user drags (scrollView.isTracking = YES). When the user scrolls towards the left and lets go (scrollView.isTracking = NO), the image views end up moving too fast towards the right and disappear almost instantly. Does anyone know how I could have the images move nicely and not disappear even when the user's not manually dragging the view and has already let go?

Here's my code for dragging horizontally:

-(void) scrollViewDidScroll:(UIScrollView *)scrollView {
    CGPoint offset = self.scrollView.contentOffset;
    CGSize size = self.scrollView.contentSize;

    CGPoint newXY = CGPointMake(size.width-600, size.height-480);

    // this bit here allows scrolling towards the right
    if (offset.x > size.width - 320) {
        [self.scrollView setContentSize:CGSizeMake(size.width+320, size.height)];
        [self.scrollView setContentOffset: offset];
    }

    // and this is where my problem is:
    if (offset.x < 0) {
        for (UIImageView *imageView in self.scrollView.subviews) {
            CGRect frame = imageView.frame;
            [imageView setFrame:CGRectMake
                (frame.origin.x+newXY.x, frame.origin.y, 200, frame.size.height)];
        }
        [self.scrollView setContentOffset:CGPointMake(newXY.x+offset.x, offset.y)];
    } 
}

EDIT: This is now working - I had a look at StreetScroller and it's all good now.

However, I now want to zoom in on the scrollview, but viewForZoomingInScrollView is never called. Is it not possible to zoom in on a scrollview with a large content size?

1条回答
对你真心纯属浪费
2楼-- · 2019-02-07 09:12

There are some approaches floating around here. Just use the site search …

If you want an more "official" example created by Apple take a look at the StreetScroller Demo. For some more information about this example take a look at last years WWDC session no. 104 Advanced Scroll View Techniques.

There is also an UIScrollView subclass on Github called BAGPagingScrollView, which is paging & infinite, but it has a few bugs you have to fix on your own, because it's not under active development (especially the goToPage: method leads to problems).

查看更多
登录 后发表回答