gpt4 book ai didi

ios - UICollectionViewFlowLayout 忽略不同高度项目的部分插图 - 错误还是预期?

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:05:14 29 4
gpt4 key购买 nike

我正在使用 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;
}

最佳答案

出于某种原因,如果您每行有一个项目,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];
}

如果您在一行中有多个单元格,则此解决方案不起作用(也不需要),因此您应该使用 bool 值或任何您喜欢的方式检查这种情况...这只是此场景的一个简单示例

关于ios - UICollectionViewFlowLayout 忽略不同高度项目的部分插图 - 错误还是预期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24165816/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com