延迟加载UICollectionViewCell的自定义子视图

时间:2013-12-06 10:33:31

标签: ios uicollectionview uicollectionviewcell

-collectionView:cellForItemAtIndexPath:我正在向UICollectionViewCell添加自定义子视图,如下所示:

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

    NSString *const cellIdentifier = @"cellIdentifier";
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];

    MyCustomViewClass *carouselView = [[MyCustomViewClass alloc] init];
    [cell.contentView addSubview:carouselView];            

    return cell;
}

根据documentationdequeueReusableCellWithReuseIdentifier:forIndexPath:“将现有单元格取消,或者根据您之前注册的类或nib文件创建新单元格。”

问题在于我cellForItemAtIndexPath的实施不断创建MyCustomViewClass的新实例。即使后者的实例在离开屏幕时从集合视图中删除,但每次调用dequeueReusableCellWithReuseIdentifier:forIndexPath:时创建一个新实例仍然是错误的。

我的问题是,鉴于MyCustomViewClass实例是图形密集型并占用内存,懒惰加载它们的最佳方法是什么?我必须实现自己的队列吗?或者我应该把它作为UICollectionViewCell的子类吗?

2 个答案:

答案 0 :(得分:2)

由于您执行了此操作MyCustomViewClass *carouselView = [[MyCustomViewClass alloc] init];,因此每次系统调用dequeueReusableCellWithReuseIdentifier:forIndexPath:时,它都会为您创建MyCustomViewClass的新实例。因此,您需要做的是检查是否已将MyCustomViewClass的实例添加到该单元格中,如果没有,则创建一个新实例。

答案 1 :(得分:1)

我不知道你的MyCustomViewClass做了什么,但你可以创建一个已经与CustomViewClass关联的自定义UICollectionViewCell。

如果您的CustomViewClass扩展UIView更简单。如果你使用故事板,那就更简单了。在故事板中,您不需要为此创建自定义UICollectionViewCell。您可以将UIVIew拖到CollectionViewCell并将customView设置为MyCustomViewClass。这样它只会被创建一次然后重复使用。

如果您的MyCustomViewClass具有某种状态(假设这是一个具有百分比的状态栏),您可以重置该状态,您必须扩展UICollectionViewCell并覆盖prepareForReuse