UICollectionView estimatedItemSize - last cell is not aligned

artysx picture artysx · Oct 25, 2014 · Viewed 9k times · Source

I want to make a usual horizontalScrolling flowLayout UICollectionView with estimatedItemSize and preferredLayoutAttributesFittingAttributes in cell. But there is something wrong with last cell. Any idea where is the issue? Project itself

enter image description here

@implementation RowCollectionView

- (instancetype) initWithFrame:(CGRect)frame collectionViewLayout:(UICollectionViewLayout *)layout
{
    if (self = [super initWithFrame:frame collectionViewLayout:layout])
    {
        [self configureRowCollectionView];
    }

    return self;
}

- (void) awakeFromNib
{
    [super awakeFromNib];

    [self configureRowCollectionView];
}

- (void) configureRowCollectionView
{
    self.backgroundColor = [UIColor lightGrayColor];

    self.dataSource = self;
    self.delegate = self;

    // Horizontal Direction
    UICollectionViewFlowLayout *flowLayout = (UICollectionViewFlowLayout *) self.collectionViewLayout;
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;

    // Estimated Item Size
    flowLayout.estimatedItemSize = CGSizeMake(self.bounds.size.height, self.bounds.size.height);


    [self registerClass:[RowCollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([RowCollectionViewCell class])];
}

- (NSInteger) collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 10;
}

- (UICollectionViewCell *) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([RowCollectionViewCell class]) forIndexPath:indexPath];

    cell.contentView.backgroundColor = [UIColor redColor];

    return cell;
}

@end

@implementation RowCollectionViewCell

- (UICollectionViewLayoutAttributes *) preferredLayoutAttributesFittingAttributes:(UICollectionViewLayoutAttributes *)layoutAttributes
{
    [super preferredLayoutAttributesFittingAttributes:layoutAttributes];

    UICollectionViewLayoutAttributes *attributes = [layoutAttributes copy];

    attributes.size = CGSizeMake(80, 80);

    return attributes;
}

@end    

Answer

Romit Kumar picture Romit Kumar · Sep 20, 2018

I face a similar issue and the problem was solved by giving a proper minimum inter item spacing, using the delegate methods - minimumInteritemSpacingForSectionAt- of UICollectionViewDelegateFlowLayout.