2013-05-30 40 views
0

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

我已经拖拽SO & Apple文档,例如我的使用自定义布局的示例,但它们都预装了布局信息。如果有人能帮助我,我应该如何实现下面的方法,我会很感激 -

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

感谢任何指针。

回答

0

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

如果你不重写它,prepareLayout什么都不做 - 在我这里,因为我不想预先加载1000s单元格的所有布局信息,所以我不重写它。

我实现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; 
} 

我意识到,这种方法被称为为每个新屏幕全,通过矩形是窗口上可见的内容,因此所有我需要做的是要返回每个项目的属性数组,这将是在那个矩形 - 我有另一个方法,frameForCellAtIndexPath:,它计算给定indexPath单元格的框架。

现在,它可以完美地工作,没有内存占用的预载。