OGeek|极客世界-中国程序员成长平台

标题: ios - UICollectionViewFlowLayout 忽略不同高度项目的部分插图 - 错误还是预期? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 10:22
标题: ios - UICollectionViewFlowLayout 忽略不同高度项目的部分插图 - 错误还是预期?

我正在使用 UICollectionViewFlowLayout 并想应用如下所示的部分插图。我所有的元素都有相同的宽度但不同的高度。当同一部分中的项目具有相同的高度时,插入有效,但当它们在同一部分中的高度不同时无效。这是此布局的预期行为吗?我需要子类化并制作一个自定义的,还是缺少一些东西?

- (UIEdgeInsets)collectionViewUICollectionView *)collectionView layoutUICollectionViewLayout*)collectionViewLayout insetForSectionAtIndexNSInteger)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;
}



Best Answer-推荐答案


由于某种原因,如果每行有一个项目,UICollectionViewFlowLayout 具有将单元格居中的行为。然后它会忽略部分插图。

您可以通过重写 UICollectionViewFlowLayout 并更改以下两个方法来解决此问题:

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPathNSIndexPath *)indexPath
{
    UICollectionViewLayoutAttributes *attribute = [super layoutAttributesForItemAtIndexPath:indexPath];

    [self fixLayoutAttributeInsets:attribute];

    return attribute;
}

- (NSArray *)layoutAttributesForElementsInRectCGRect)rect
{
    NSArray *results = [super layoutAttributesForElementsInRect:rect];

    for (UICollectionViewLayoutAttributes *attribute in results)
    {
        [self fixLayoutAttributeInsets:attribute];
    }

    return results;
}

魔法:

- (void)fixLayoutAttributeInsetsUICollectionViewLayoutAttributes *)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] respondsToSelectorselector(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/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4