1

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.

fatihyildizhan
  • 8,614
  • 7
  • 64
  • 88
meteors
  • 1,747
  • 3
  • 20
  • 40
  • Why do you need to shift the x-coordinates? The coordinates should remain fixed. With each page-swipe you should only need to remove a view from the end, and calculate the coordinates for the opposite end and add the new view there. – TomSwift Jul 24 '15 at 19:23
  • But that would leave an empty space at first position. Thus there would be blank space of scroll view background color at the left most position during moving right. – meteors Jul 24 '15 at 19:30
  • Don't remove it until the scrolling has stopped. That position is off-screen. Plus you said you have a buffer of 3 views on either side, which are also off-screen. – TomSwift Jul 24 '15 at 19:53
  • I only remove them after scrolling by a particular offset. And the particular offset if equal to page width or screen width in this case. – meteors Jul 25 '15 at 09:46

1 Answers1

0

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.

meteors
  • 1,747
  • 3
  • 20
  • 40