UICollectionView sorts cells automatically UICollectionViewFlowLayout
I am currently working on automating cells that are new in iOS8
.
According to the WWDC 2014 video "What's New in the table and a collection of" all that is required for the automatic sorting of cells - it is set estimatedSize
in the UICollectionViewFlowLayout
specified in the initialization UICollectionView
, and override sizeThatFits:
in UICollectionViewCell
.
Initialization
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
[flowLayout setEstimatedItemSize:CGSizeMake(146.0f, 156.0f)];
_collectionView = [[UICollectionView alloc] initWithFrame:[_containerView bounds] collectionViewLayout:flowLayout];
sizeThatFits
in my cell where _userLabel is the label that sits at the bottom and marks the actual height.
- (CGSize)sizeThatFits:(CGSize)size
{
CGSize actualSize = CGSizeMake([[self contentView] bounds].size.width, [_userLabel frame].origin.x + [_userLabel bounds].size.height);
return actualSize;
}
It turns out that the actual size has a greater height than my calculated size, which should be fine, and the cell actually resizes in height correctly.
Now with iPhone6 ββand 6+, the width may differ as well. I want the cells to display the screen width correctly. So I have applied three delegate methods in UICollectionViewFlowLayout; my first intuition is to calculate the width that I want the cells to have screen width, section inserts and paragraph spacing.
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
UIEdgeInsets sectionInsets = [self collectionView:collectionView layout:collectionViewLayout insetForSectionAtIndex:[indexPath section]];
CGFloat interItemSpacing = [(UICollectionViewFlowLayout *) collectionViewLayout minimumInteritemSpacing];
CGFloat cellWidth = ([_collectionView bounds].size.width - sectionInsets.left - sectionInsets.right - interItemSpacing) / 2;
CGSize collectionViewCellSize = CGSizeMake(cellWidth, 156.0f);
return collectionViewCellSize;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
return 12.0f;
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
return UIEdgeInsetsMake(10.0f, 10.0f, 10.0f, 10.0f);
}
It works, however, in part. The CollectionView will not respect insertion of the top section, and when scrolling through the CollectionView, selecting another tab and then back again, the cells seem to have disappeared.
Apparently I am doing something wrong, but I cannot figure out where. Anyone got it?
source to share
No one has answered this question yet
Check out similar questions: