Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

ios - How to expand UICollectionView contentSize when paging enable?

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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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];
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...