启用分页时如何扩展UICollectionView contentSize? [英] How to expand UICollectionView contentSize when paging enable?

查看:112
本文介绍了启用分页时如何扩展UICollectionView contentSize?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个启用了分页机制的简单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.

如何展开UICollectionViewcontentSize,以使最后一页不包含上一页的任何单元格?

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 + spacing)

推荐答案

您需要继承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);
}

旁注,当您使用自定义布局时,您将无法在界面生成器"中设置某些显示属性.您可以在自定义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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆