While studying iOS6 new features I got a question about UICollectionView.
I am currently testing it with Flow layout and the scroll direction set to horizontal, scrolling and paging enabled. I've set its size to exactly the same as my custom's cells, so it can show one at a time, and by scrollig it sideways, the user would see the other existing cells.
It works perfectly.
Now I want to add and UIPageControl to the collection view I made, so it can show up which cell is visible and how many cells are there.
Building up the page control was rather simple, frame and numberOfPages defined.
The problem I am having, as the question titles marks, is how to get which cell is currently visible in the collection view, so it can change the currentPage of the page control.
I've tried delegate methods, like cellForItemAtIndexPath, but it is made to load cells, not show them. didEndDisplayingCell triggers when a cell its not displayed anymore, the opposite event of what I need.
Its seems that -visibleCells and -indexPathsForVisibleItems, collection view methods, are the correct choice for me, but I bumped into another problem. When to trigger them?
Thanks in advance, hope I made myself clear enough so you guys can understand me!
I know this is an old one but I've just needed to implement this sort of feature again and have a bit to add which gives a more complete answer.
Firstly: Using
scrollViewDidEndDecelerating
assumes that the user lifted their finger while dragging (more like a flick action) and therefore there is a deceleration phase. If the user drags without lifting the finger theUIPageControl
will still indicate the old page from before the drag began. Instead using thescrollViewDidScroll
callback means that the view is updated both after dragging and flicking and also during dragging and scrolling so it feels much more responsive and accurate for the user.Secondly: Relying on the
pagewidth
for calculating the selected index assumes all the cells have the same width and that there is one cell per screen. taking advantage of theindexPathForItemAtPoint
method onUICollectionView
gives a more resilient result which will work for different layouts and cell sizes. The implementation below assumes the centre of the frame is the desired cell to be represented in thepagecontrol
. Also if there are intercell spacings there will times during scrolling when the selectedIndex could be nil or optional so this needs to be checked and unwrapped before setting on the pageControl.One more thing - set the number of pages on the
UIPageControl
with something like this: