iOS: ScrollView infinite paging - Duplicate end caps

你离开我真会死。 提交于 2019-11-28 11:33:01

Better still, you don't need to have duplicate view A's and duplicate view C's, you just move them around in - (void)scrollViewDidScroll:(UIScrollView *)scrollView while manipulating the contentOffset.

Setup: probably very similar to how you already do it.

Set your UIScrollView to have contentSize 3 times it's bounds width. Make sure paging is turned on and bouncing off.

Add your ABC subviews to the UIScrollView from left to right.

Also have an array in your ViewController called _contentViews that contains your UIViews ABC.

Then implement this which will reset the content offset and move your subviews around at the same time when the scrollview reaches the edges:

-(void)scrollViewDidScroll:(UIScrollView *)scrollView {

    if(scrollView.contentOffset.x == 0) {
        CGPoint newOffset = CGPointMake(scrollView.bounds.size.width+scrollView.contentOffset.x, scrollView.contentOffset.y);
        [scrollView setContentOffset:newOffset];
        [self rotateViewsRight];
    }
    else if(scrollView.contentOffset.x == scrollView.bounds.size.width*2) {
        CGPoint newOffset = CGPointMake(scrollView.contentOffset.x-scrollView.bounds.size.width, scrollView.contentOffset.y);
        [scrollView setContentOffset:newOffset];
        [self rotateViewsLeft];
    }
}

-(void)rotateViewsRight {
    UIView *endView = [_contentViews lastObject];
    [_contentViews removeLastObject];
    [_contentViews insertObject:endView atIndex:0];
    [self setContentViewFrames];

}

-(void)rotateViewsLeft {
    UIView *endView = _contentViews[0];
    [_contentViews removeObjectAtIndex:0];
    [_contentViews addObject:endView];
    [self setContentViewFrames];

}

-(void) setContentViewFrames {
    for(int i = 0; i < 3; i++) {
        UIView * view = _contentViews[i];
        [view setFrame:CGRectMake(self.view.bounds.size.width*i, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!