Pack CollectionViewCells tightly together on iOS?

2019-07-15 08:37发布

If you want to to pack the cells neatly together even if some of the other content in another cell is bigger, how do one do that?

If you look at the picture below, the first string is the biggest, but if I want to pack the other cells as neatly and tightly together as the first one, regardless of the size, how is this done?

I want to do this regardless of the size both from the sides and up and down. I want the cells to be laid out as the arrows in this picture are pointing.

UPDATE: the first line of text is two cells packed togheter.

ONE CELL WITH STRING PACKED NEATLY TOGETHER, AND THE OTHER ARE FAR AWAY FROM EACH OTHER, THIS IS BECAUSE THE FIRST STRING IS THE LONGEST

1条回答
兄弟一词,经得起流年.
2楼-- · 2019-07-15 09:24

You have to use UICollectionViewFlowLayout to achieve this

Note: Below information's are taken from Raywenderlich blog

You can subclass UICollectionViewLayout to create your own custom layouts , but Apple has graciously provided developers with a basic “flow-based” layout called UICollectionViewLayout. It lays elements out one after another based on their size, quite like a grid view. You can use this layout class out of the box, or subclass it to get some interesting behavior and visual effects.

You can see a good example in Raywenderlich blog

Example code:

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    NSString *searchTerm = self.searches[indexPath.section]; FlickrPhoto *photo =
    self.searchResults[searchTerm][indexPath.row];

    CGSize retval = photo.thumbnail.size.width > 0 ? photo.thumbnail.size : CGSizeMake(100, 100);
    retval.height += 35; retval.width += 35; return retval;
}


- (UIEdgeInsets)collectionView:
(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(50, 20, 50, 20); 
}

There are more delegate methods you can implement than this. Examples are given below

collectionView:layout:sizeForItemAtIndexPath
collectionView:layout:insetForSectionAtIndex:
查看更多
登录 后发表回答