Search code examples
iosuiscrollviewviewpage

Adding and removing views from UIScrollView on iOS


I'm trying to implement a view pager using horizontal UIScrollView. The view pager may contain many views. I'm using UIScrollview with pagingEnabled to true. The problem is that I cannot have all the views in the memory at the same time as there can be around 40-50 different views. So I decided to load the current view and its adjacent 3 views on both sides (right and left). When I scroll then using scrollViewDidScroll method I remove a view from the left and insert a new view to the right. For doing this I do the following:

  • First, check whether the scroll is right scroll or left then if a complete page is scrolled or not.
  • Then (for the right scroll) I remove the left most view from superView (i.e. is scrollView).
  • Move the x co-ordinate of remaining views to the left.
  • Add a new subview to the right.
  • Change the content size of the scroll view accordingly.

Somehow the above implementation is not working properly, especially the one involving changing the x co-ordinates. I think that I'm missing something and trying to solve the problem of manipulating views within scrollView in the wrong manner. This is the link to the demo project that I implemented on GitHub. Please any help regarding problems in the current implementation or any other idea as to how to implement it another way is very much welcome.

NOTE: This code has one more bug already while swiping on the right from the first view to the second view which happens sometimes. I couldn't find any solution to that either. The stack trace of that problem is here.


Solution

  • Ok so actually the approach of shrinking and expanding scrollView content size is not the correct approach (at least in my scenario). As I already the number of views will remain fixed, I set the contentSize fixed to number of views * screen width. Now each time I just use removeFromSuperview() to remove them from scrollView and add a new one to scrollView in scrollViewDidScroll() method.

    The complete working project is updated here.