对你们大多数人来说,这可能是很明显的,但是花了我一点时间才弄明白。
如果你不重写它,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单元格的框架。
现在,它可以完美地工作,没有内存占用的预载。