UICollectionView estimatedItemSize - 最后一个单元格未对齐
我想在单元格中使用estimatedItemSize和preferredLayoutAttributesFittingAttributes制作一个通常的horizontalScrolling flowLayout UICollectionView。但最后一个细胞有问题。知道问题在哪里?
项目本身
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
@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
你调用super方法但你没有使用super返回的layoutAttributes。
You call super method but you did not use super returned layoutAttributes.
[super preferredLayoutAttributesFittingAttributes:layoutAttributes];
您可以尝试打印原始layoutAttributes和super的layoutAttributes。
有时,您不需要调用超级函数。
You can try to print out original layoutAttributes vs super's layoutAttributes. Sometimes, you don't need to call super function.
其次,您可以创建自定义flowlayout或set inset以让您的单元格对齐顶部。我在我的项目中这样做了。
Second, You can create custom flowlayout or set inset to let your cell align top. I did this in my project.