I'm making a simple UICollectionView
with a paging mechanism enabled, and everything works fine. Though, when scroll to the last page the number of the cells are not fully visible in the screen, and the last page contains some cells of the previous page.
How do I expand the contentSize
of the UICollectionView
so that the last page doesn't contain any cells of the previous page?
An example here: the UICollectionView
scrolls horizontally with 6 cells, this way:
Page 1: cell0 - cell1 - cell2 - cell3
Scroll: cell2-cell3-cell4-cell5 // Not expected: how to change to: cell4 - cell 5 in page2.
SUMMARY:
I want to set
collectionView.contentSize = numberOfPage * collectionView.frame
NOT
collectionView.contentSize = numberOfCell * (cellFrame + spacing)
I have an answer that doesn't require any subclassing.
In -viewDidLoad, calculate how many items per page you will have and how many pages you will have. Store these values in properties.
Then in -collectionView:numberOfItemsInSection: just lie to it:
You will of course have more cells than content, right? So in -collectionView:cellForItemAtIndexPath: just return nil for the extra cells:
There you go: full, scrollable final page. In my opinion, the horizontal scroll mode should just default to this.
For horizontal paging
I think you have to subclass
UICollectionViewLayout
and create your custom layout to manage these kind of problems.You need to subclass
UICollectionViewLayout
and override thecollectionViewContentSize
method. I subclassedUICollectionViewFlowLayout
so I wouldn't have to re-write all the layout code.I'm building a 4x4 grid, so my method looks like this:
Side note, when you use a custom layout, you lose the ability to set the some of the display properties in the Interface Builder. You can set them programatically in the
init
method of your custom UICollectionViewLayout subclass. Here's mine for reference:The answer works well, though for our code we had one section per page. So it meant the override for our layout class was just
You can adjust the content with the
viewDidLayoutSubviews:
method. This method gets called when the collection view and all the cells are placed in theview
, so that you can adjust cell.