5

我正在使用自定义布局来获取使用 UICollectionReusableView 的子类的几个背景颜色部分。这是代码:

- (void)prepareLayout 
{
    [super prepareLayout];

    self.itemAttributes = [NSMutableArray new];
    NSInteger numberOfSection = self.collectionView.numberOfSections;
    for (int section = 0; section < numberOfSection; section++) {
        if (section == self.decorationViewOfKinds.count)
            break;

        NSString *decorationViewOfKind = self.decorationViewOfKinds[section % self.decorationViewOfKinds.count];
        if ([decorationViewOfKind isKindOfClass:[NSNull class]])
            continue;

        NSInteger lastIndex = [self.collectionView numberOfItemsInSection:section] - 1;
        if (lastIndex < 0)
        continue;

        UICollectionViewLayoutAttributes *firstItem = [self layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:section]];
        UICollectionViewLayoutAttributes *lastItem = [self layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForRow:lastIndex inSection:section]];

        CGRect frame = CGRectUnion(firstItem.frame, lastItem.frame);
        frame.origin.x -= self.sectionInset.top;
        frame.size.height += self.sectionInset.bottom;

        if (self.scrollDirection == UICollectionViewScrollDirectionHorizontal) {
            frame.size.width += self.sectionInset.left + self.sectionInset.right;
            frame.size.height = self.collectionView.frame.size.height;
        }
        else {
            frame.size.width = self.collectionView.frame.size.width;
            frame.size.height += self.sectionInset.top + self.sectionInset.bottom;
        }

        UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForDecorationViewOfKind:decorationViewOfKind withIndexPath:[NSIndexPath indexPathForRow:0 inSection:section]];
        attributes.zIndex = -1;
        attributes.frame = frame;
        [self.itemAttributes addObject:attributes];
        [self registerNib:[UINib nibWithNibName:decorationViewOfKind bundle:[NSBundle mainBundle]] forDecorationViewOfKind:decorationViewOfKind];
    }
}

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
    NSMutableArray *attributes = [NSMutableArray arrayWithArray:[super layoutAttributesForElementsInRect:rect]];
    for (UICollectionViewLayoutAttributes *attribute in self.itemAttributes) {
        if (!CGRectIntersectsRect(rect, attribute.frame))
            continue;

        [attributes addObject:attribute];
    }

    return attributes;
}

此代码有时会在使用 iOS 8.4.1 的设备上崩溃,并抛出:

致命异常:NSInternalInconsistencyException 没有 -layoutAttributesForDecorationViewOfKindOfKind 的 UICollectionViewLayoutAttributes 实例:路径 {length = 2,path = 2 - 0} 处的 AlbumsSectionBackgroundDecoratorView

它不会发生在模拟器中,只会发生在 iOS 8.4.1 的设备中

有任何想法吗?谢谢!

编辑

该错误似乎正在发生,导致 UICollectionView 出现背压。我避免重新加载 UICollectionView 并且似乎工作正常

4

0 回答 0