启用分页时如何扩展 UICollectionView contentSize? [英] How to expand UICollectionView contentSize when paging enable?
问题描述
我正在制作一个启用了分页机制的简单 UICollectionView
,一切正常.但是,当滚动到最后一页时,单元格的数量在屏幕上并不完全可见,并且最后一页包含上一页的一些单元格.
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.
如何扩展UICollectionView
的contentSize
,使最后一页不包含上一页的任何单元格?
How do I expand the contentSize
of the UICollectionView
so that the last page doesn't contain any cells of the previous page?
一个示例这里:UICollectionView
水平滚动 6 个单元格,这样:
An example here: the UICollectionView
scrolls horizontally with 6 cells, this way:
第 1 页:
cell0 - cell1 - cell2 - cell3
第 2 页:
cell4 - cell5
是预期的,但出乎意料
cell4 - cell5
is expected, but unexpectedly
cell2 - cell3 - cell4 - cell5
怎么改?
总结:
我要设置
collectionView.contentSize = numberOfPage * collectionView.frame
不是
collectionView.contentSize = numberOfCell * (cellFrame + 间距)
推荐答案
你需要继承 UICollectionViewLayout
并重写 collectionViewContentSize
方法.我对 UICollectionViewFlowLayout
进行了子类化,因此我不必重新编写所有布局代码.
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.
我正在构建一个 4x4 网格,所以我的方法如下所示:
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);
}
旁注,当您使用自定义布局时,您将无法在 Interface Builder 中设置某些显示属性.您可以在自定义 UICollectionViewLayout 子类的 init
方法中以编程方式设置它们.这是我的参考:
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];
}
这篇关于启用分页时如何扩展 UICollectionView contentSize?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!