如何在分页启用时展开UICollectionView contentSize?
我正在做一个简单的UICollectionView
启用分页机制,一切工作正常。 但是,当滚动到最后一页时,单元格的数量在屏幕上并不完全可见,最后一页包含上一页的一些单元格。
如何展开UICollectionView
的contentSize
,使最后一页不包含前一页的任何单元格?
这里是一个例子: UICollectionView
以6个单元格水平滚动,如下所示:
第1页: cell0 - cell1 - cell2 - cell3
滚动:cell2-cell3-cell4-cell5 //不期望:如何更改为:cell4 – 第2页中的单元格5。
概要:
我想设置
collectionView.contentSize = numberOfPage * collectionView.frame
不
collectionView.contentSize = numberOfCell * (cellFrame + spacing)
您需要UICollectionViewLayout
并覆盖collectionViewContentSize
方法。 我subclassed UICollectionViewFlowLayout
所以我不会重新写所有的布局代码。
我正在构build一个4×4的网格,所以我的方法如下所示:
- (CGSize)collectionViewContentSize { NSInteger itemCount = [self.collectionView numberOfItemsInSection:0]; NSInteger pages = ceil(itemCount / 16.0); return CGSizeMake(320 * pages, self.collectionView.frame.size.height); }
注意,当您使用自定义布局时,将无法在Interface Builder中设置一些显示属性。 您可以在自定义的UICollectionViewLayout子类的init
方法中以编程方式设置它们。 这里是我的参考:
- (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(CollectionView.pagingEnabled) { int numberOfPages = floor(collectionView.contentSize.width / collectionView.frame.size.width) + 1; CGFloat float requierdWidth=self.collectionView.frame.size.width*numberOfPages; self.Layout.footerReferenceSize=CGSizeMake(requierdWidth-self.collectionView.contentSize.width,0); }
答案很好,但是对于我们的代码,我们每页都有一个部分。 所以这意味着我们的布局类的覆盖只是
-(CGSize) collectionViewContentSize { return CGSizeMake(CGRectGetWidth(self.collectionView.frame) * [self.collectionView numberOfSections], CGRectGetHeight(self.collectionView.frame)) ; }
我想你必须UICollectionViewLayout
并创build自定义布局来pipe理这些types的问题。
我有一个不需要任何子类的答案。
在-viewDidLoad中,计算每个页面有多less项目,以及您将拥有多less页面。 将这些值存储在属性中。
self.numberOfItemsPerPage = NumberOfRows * NumberOfColumns; self.numberOfPages = ceilf((CGFloat)self.items.count / (CGFloat)self.numberOfItemsPerPage);
然后在-collectionView:numberOfItemsInSection:只是对它说谎:
return self.numberOfItemsPerPage * self.numberOfPages;
你当然会拥有比内容更多的单元格,对吗? 所以在-collectionView:cellForItemAtIndexPath:只是返回零为额外的单元格:
if (indexPath.item > [self.items count] - 1) { //We have no more items, so return nil. This is to trick it to display actual full pages. return nil; }
你去:完整的,可滚动的最后一页。 在我看来,水平滚动模式应该默认为这个。
您可以使用viewDidLayoutSubviews:
方法调整内容。 当收集视图和所有单元格放置在view
时调用此方法,以便您可以调整单元格。