• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

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

[复制链接]
菜鸟教程小白 发表于 2022-12-12 10:22:22 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

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

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap