我正在使用UICollectionViewFlowLayout并想要应用下面的部分插入。我的所有物品都有相同的宽度,但高度不同。当同一部分中的项目具有相同的高度但是当它们在同一部分中具有不同的高度时,插图工作。这种布局的预期行为是什么?我是否需要子类化并制作自定义的或缺少的东西?
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
UIEdgeInsets insets = UIEdgeInsetsZero;
CGFloat big = 30;
CGFloat small = 10;
if (section < 5) {
insets = UIEdgeInsetsMake(0, big, 0, small);
} else {
insets = UIEdgeInsetsMake(0, small, 0, big);
}
return insets;
}
答案 0 :(得分:4)
出于某种原因,如果每行都有一个项目,则UICollectionViewFlowLayout具有使单元格居中的行为。它会忽略部分插入。
您可以通过覆盖UICollectionViewFlowLayout并更改以下两种方法来解决此问题:
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewLayoutAttributes *attribute = [super layoutAttributesForItemAtIndexPath:indexPath];
[self fixLayoutAttributeInsets:attribute];
return attribute;
}
和
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
NSArray *results = [super layoutAttributesForElementsInRect:rect];
for (UICollectionViewLayoutAttributes *attribute in results)
{
[self fixLayoutAttributeInsets:attribute];
}
return results;
}
神奇:
- (void)fixLayoutAttributeInsets:(UICollectionViewLayoutAttributes *)attribute
{
if ([attribute representedElementKind])
{ //nil means it is a cell, we do not want to change the headers/footers, etc
return;
}
//Get the correct section insets
UIEdgeInsets sectionInsets;
if ([[[self collectionView] delegate] respondsToSelector:@selector(collectionView:layout:insetForSectionAtIndex:)])
{
sectionInsets = [(id<UICollectionViewDelegateFlowLayout>)[[self collectionView] delegate] collectionView:[self collectionView] layout:self insetForSectionAtIndex:[[attribute indexPath] section]];
}
else
{
sectionInsets = [self sectionInset];
}
//Adjust the x position of the view, the size should be correct or else do more stuff here
CGRect frame = [attribute frame];
frame.origin.x = sectionInsets.left;
[attribute setFrame:frame];
}
如果单行上有多个单元格,则此解决方案不起作用(并且不需要),因此您应该使用布尔值或任何您喜欢的内容检查该情况...这只是此场景的一个简单示例< / p>
答案 1 :(得分:-2)
似乎不可能有不同的高度,所以我使单元格全宽并且在单元类本身内管理填充逻辑。