werbary werbary - 6 months ago 63
iOS Question

UIScrollView with "Circular" scrolling

I am trying to make "Circular" scrolling in my UIScrollView, but unsuccessful.

What I want to do:
if uiscrollview reaches end, it should move to start
if uiscrollview at start and moving back, it should move to end

Appending scrollview isn't good way in my situation (other methods should get "page id")

Have you any ideas?


I've implemented this method, but it requires paging enabled. Lets assume you have five elements A,B,C,D and E. When you set up your view, you add the last element to the beginning and the first element to the end, and adjust the content offset to view the first element, like this E,[A],B,C,D,E,A. In the UIScrollViewDelegate, check if the user reach any of the ends, and move the offset without animation to the other end.

Imagine the [ ] indicates the view being shown:


User swipes right


User swipes right


Then, automatically set the content offset to the second element


This way the user can swipe both ways creating the illusion of an infinite scroll.



I've uploaded a complete implementation of this algorithm. It's a very complicated class, because it also has on-click selection, infinite circular scroll and cell reuse. You can use the code as is, modify it or extract the code that you need. The most interesting code is in the class TCHorizontalSelectorView.

Link to the file

Enjoy it!

Update 2

UICollectionView is now the recommended way to achieve this and it can be used to obtain the very same behavior. This tutorial describes in details how to achieve it.