如何使用集合视图布局(不是流布局)和UICollectionViewLayoutInvalidationContext制作粘贴标头?

时间:2016-12-10 06:12:15

标签: ios uicollectionview uicollectionviewlayout

我想在我的集合视图布局中实现粘性标头,但是要有效。我查看了苹果文档,发现了UICollectionViewLayoutInvalidationContext。

我将此对象与自定义集合视图布局一起实现。我的目标是在集合视图滚动时实现不调用prepareLayout

我在自定义集合视图布局中编写了以下代码:

- (BOOL) shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds{
    return YES;
}

+ (Class)invalidationContextClass{
    return [InvalidationContext class];
}

- (void)invalidateLayoutWithContext:(UICollectionViewLayoutInvalidationContext *)context{

    NSMutableArray * indexPaths = [NSMutableArray new];

    NSInteger numberOfSections = self.collectionView.numberOfSections;

    for (NSInteger section = 0; section < numberOfSections; section++) {
        NSInteger numberOfItemsInSection = [self.collectionView numberOfItemsInSection:section];
        if (numberOfItemsInSection > 0) {
            [indexPaths addObject:[NSIndexPath indexPathForRow:0 inSection:section]];
        }
    }

    [context invalidateItemsAtIndexPaths:indexPaths];
    [super invalidateLayoutWithContext:context];
}

这是我的UICollectionViewLayoutInvalidationContext子类:

#import "InvalidationContext.h"

@implementation InvalidationContext

- (BOOL)invalidateEverything {
    return NO;
}

@end

有人可以帮我发现错误吗?

注意: 我的粘贴标题是每个部分的第一行。我也没有启用实现具有补充视图的标头。

1 个答案:

答案 0 :(得分:0)

是的,有了补充视图,我可以有效地实现我的自定义集合视图布局与粘性标头。如果有人想看我的代码,请随意提问。