如何在 UICollectionView 顶部制作粘性标题

Tes*_* 87 1 header objective-c collectionview ios

目前我的 UICollectionView 中有一个标题单元格。当我尝试滚动 UICollectionView 时,标题单元格将与 UICollectionView 列表一起滚动。我可以知道如何将标题单元格设置在顶部吗?请帮忙。谢谢。

我目前的结果:- 在此输入图像描述

我的预期结果:- 在此输入图像描述

这是我的 ViewController 中标题单元格的示例代码:-

- (UICollectionView *)collectionView
{
    if (!_collectionView) {
        DCHoverFlowLayout *layout = [DCHoverFlowLayout new];
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.frame = CGRectMake(0, DCTopNavH, ScreenW, ScreenH - DCTopNavH);

        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;

        [_collectionView registerClass:[Product_HeadView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:Product_HeadViewID];

    }
    return _collectionView;
}



- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {

    UICollectionReusableView *reusableview = nil;
    if (kind == UICollectionElementKindSectionHeader){

        Product_HeadView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:Product_HeadViewID forIndexPath:indexPath];
        WEAKSELF

  };
        reusableview = headerView;
        return cell;
    }

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{

    _lastContentOffset = scrollView.contentOffset.y;

}
-(void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView
{

    if(scrollView.contentOffset.y > _lastContentOffset){
        [self.navigationController setNavigationBarHidden:YES animated:YES];
        self.collectionView.frame = CGRectMake(0, 20, ScreenW, ScreenH - 20);

        self.view.backgroundColor = [UIColor whiteColor];
    }else{
        [self.navigationController setNavigationBarHidden:NO animated:YES];
        self.collectionView.frame = CGRectMake(0, DCTopNavH, ScreenW, ScreenH - DCTopNavH);

        self.view.backgroundColor = ThemeBackgroundColor;
    }
}

#pragma mark - <UIScrollViewDelegate>
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //Detect Button Visible
    _backTopButton.hidden = (scrollView.contentOffset.y > ScreenH) ? NO : YES;


    WEAKSELF
    [UIView animateWithDuration:0.25 animations:^{
        __strong typeof(weakSelf)strongSelf = weakSelf;
        strongSelf.footprintButton.dc_y = (strongSelf.backTopButton.hidden == YES) ? ScreenH - 60 : ScreenH - 110;
    }];

}
Run Code Online (Sandbox Code Playgroud)

更新:-

应用 Ted 的代码后,结果如下,应用程序将崩溃。 在此输入图像描述

Vla*_*yov 6

tedd答案的 Swift 版本:

let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.sectionHeadersPinToVisibleBounds = true
Run Code Online (Sandbox Code Playgroud)