UICollectionViewLayout可能包含数百万个项目

时间:2013-05-30 08:59:58

标签: uicollectionview uicollectionviewlayout

所以我有一个使用自定义布局的UICollectionView。我使用prepareLayout来设置属性,但现在我的数据集已经增长并从数据库中提取信息&可能存在数百万项 - 显然我无法存储这么多的属性(事实上它会因内存问题而崩溃)。

我拖着SO&像我这样使用自定义布局的示例的Apple Docs,但它们都预加载了布局信息。如果有人可以帮助我实现以下方法,我将不胜感激 -

-(void)prepareLayout // does this actually need to do anything in my case?
-(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect // how do I calculate this on the fly?

感谢您的任何指示。

1 个答案:

答案 0 :(得分:0)

对你们大多数人来说这可能是显而易见的,但我花了一点时间来弄明白。

如果你不覆盖它,prepareLayout什么都不做 - 在我的情况下,因为我不想预加载1000个单元格的所有布局信息,我不会覆盖它。

我对layoutAttributesForElementsInRect的实现:在这里 -

-(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
    NSMutableArray *allAttributes = [NSMutableArray array];

    NSInteger startItem = MAX(0, (NSInteger)(rect.origin.y / self.cellHeight) * kDaysInWeek);    
    NSInteger endItem = MIN(kNumDaysInCalendar, startItem + (NSInteger)((rect.size.height / self.cellHeight + 1)) * kDaysInWeek);

    for (int i = startItem; i < endItem; i++)
    {
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
        UICollectionViewLayoutAttributes *layoutAttributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
        layoutAttributes.frame = [self frameForCellAtIndexPath:indexPath];

        [allAttributes addObject:layoutAttributes];
    }

    return allAttributes;
}

我意识到每个新屏幕都会调用此方法,通过的rect是可见内容的窗口,所以我需要做的就是为每个项目返回一个属性数组。 - 我有另一个方法frameForCellAtIndexPath:,它计算给定indexPath处的单元格的帧。

现在它可以完美地完成没有占用内存的预加载。