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
Page 2:
cell4 - cell5
is expected, but unexpectedly
cell2 - cell3 - cell4 - cell5
How to change it?
SUMMARY:
I want to set
collectionView.contentSize = numberOfPage * collectionView.frame
NOT
collectionView.contentSize = numberOfCell * (cellFrame + spacing)
You need to subclass UICollectionViewLayout
and override the collectionViewContentSize
method. I subclassed UICollectionViewFlowLayout
so I wouldn't have to re-write all the layout code.
I'm building a 4x4 grid, so my method looks like this:
- (CGSize)collectionViewContentSize { NSInteger itemCount = [self.collectionView numberOfItemsInSection:0]; NSInteger pages = ceil(itemCount / 16.0); return CGSizeMake(320 * pages, self.collectionView.frame.size.height); }
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:
- (id)init { self = [super init]; if (self) { [self setup]; } return self; } - (id)initWithCoder:(NSCoder *)aDecoder { self = [super init]; if (self) { [self setup]; } return self; } - (void)setup { self.itemSize = CGSizeMake(65.0f, 65.0f); self.minimumLineSpacing = 15; self.sectionInset = UIEdgeInsetsMake(7.5f, 7.5f, 30.0f, 7.5f); [self setScrollDirection:UICollectionViewScrollDirectionHorizontal]; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With