【问题标题】:Display section header on top with UICollectionViewFlowLayout scrolling set to horizontal在顶部显示部分标题,并将 UICollectionViewFlowLayout 滚动设置为水平
【发布时间】:2026-02-04 03:45:01
【问题描述】:

这是this question 的副本。我再次询问,因为接受的答案不起作用,并且没有人提供更多关于假定正确答案如何工作的解释。

所以情况如下:我想将集合视图显示在一行中。为此,我将自定义UICollectionViewFlowLayout 应用到集合视图并将滚动设置为水平。一切正常,除了部分标题消失了。

为了解决这个问题,我实现了这个功能:

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section 
  {
    return CGSizeMake(350, 35);
  }

现在显示了标题,但问题是它显示在单元格的左侧,而不是通常的顶部。

我在寻找解决方案时偶然发现了上面的链接,但正如我所说,接受的答案根本不起作用,我找不到关于这种情况的其他解决方案。那么有人可以在这里帮助我吗?

【问题讨论】:

  • 我现在面临同样的问题。你怎么能管理它?如果您必须解决,请与我分享。谢谢
  • 嗨图伦。不幸的是,我找不到任何解决方案。我决定改为创建一个自定义视图。
  • 嗨安娜。我用另一种解决方案来解决这个问题。我用多个UICollectionView 做到了。这很容易做到并且非常方便。 :)

标签: ios uicollectionview uicollectionviewlayout


【解决方案1】:

我们可以通过使用委托方法来做到这一点 -

(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section

并保持左插图为补充视图宽度的负值并管理顶部插图

【讨论】:

    【解决方案2】:

    您是否尝试过使用类似这样的标题?

    首先:在 viewDidLoad 中设置...

    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.headerReferenceSize = CGSizeMake(self.collectionView.bounds.size.width, 30);
    // add any other setup you need
    [self.collectionView setCollectionViewLayout:flowLayout];
    

    第二:添加标题视图...

    #define LABEL_TAG 128
    
    - (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
        UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:
                                                UICollectionElementKindSectionHeader withReuseIdentifier:@"SectionHeader" forIndexPath:indexPath];
        UILabel *label = (UILabel *)[headerView viewWithTag:LABEL_TAG];
        if (!label) {
            label = [[UILabel alloc] initWithFrame:CGRectInset(headerView.bounds, 5, 5)];
            label.tag = MY_HEADER_LABEL_TAG;
            label.font = [UIFont boldSystemFontOfSize:12];
            label.textColor = [UIColor redColor];
            [headerView addSubview:label];
        }
    
        label.text = [NSString stringWithFormat:@"Section %d", indexPath.section];
        return headerView;
    }
    

    【讨论】: