Search code examples
uiscrollviewios6scrolluicollectionviewuicollectionviewcell

UICollectionView horizontal continuous loop


So I have a UICollectionView with custom UIViews for each cell. The UIView takes up the whole screen and you can horizontally navigate to each of the 4 different UIView/cells. This all works fine and uses a pager to indicate which page of the collectionview you are on.

I have looked around google and the like to see if I could get it to loop back to the beginning after you navigate passed the last cell. So for example:

I start at the 3rd cell, navigate to the 4th, then when i swipe to the right, it will go back to the first cell (pager will reflect that you are on the first page) and continue on from there.

Is this easy to do? Or am I missing something?

Thanks, Jake


Solution

  • You only need 3 UIViews, to hold the image to the left of your current view, the image to the right of the current view, and the middle view, the one that is currently onscreen.

    So lets say we have UIImages A B C D and UIViews 1 2 and 3

    We are looking at View 2, image B. Page left will take us to image A, page right to image C.

    As you swipe left/ page right, view 3 becomes the onscreen view with image C. When paging comes to rest, you swap the views contents around so the user is actually looking at the middle UIView2 again, with image C. View 1 has image B, view 3 has image D.

    Scroll right again, and do the same shuffle. Now you have

    View 1 -> image C
    View 2 -> image D
    View 3 -> image A
    

    Next page right

    View 1 -> image D
    View 2 -> image A
    View 3 -> image B
    

    so on, ad infinitum in either direction

    There is a nice WWDC video on this subject from 2011. Its worth digging out. It's the UIScrollView demo video (Documentation as PDF) You don't need Collection Views to do this, although there is no reason why you shouldn't...