【问题标题】:Lazy loading custom subviews for UICollectionViewCell延迟加载 UICollectionViewCell 的自定义子视图
【发布时间】:2013-12-06 10:33:31
【问题描述】:

-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 的子类?

【问题讨论】:

    标签: ios uicollectionview uicollectionviewcell


    【解决方案1】:

    因为你做了这个MyCustomViewClass *carouselView = [[MyCustomViewClass alloc] init];,每次系统调用dequeueReusableCellWithReuseIdentifier:forIndexPath:它都会为你创建一个MyCustomViewClass的新实例。所以你需要做的是检查MyCustomViewClass的实例是否已经被添加到那个单元格中,如果没有,则创建一个新的。

    【讨论】:

    • 谢谢,我试过了,但没用。从dequeueReusableCellWithReuseIdentifier 返回的所有单元格都有一个空的subviews 数组(即cell.contentView.subviews 始终为空)
    【解决方案2】:

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

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

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

    【讨论】:

    • 那行得通。我创建了一个自定义 UICollectionViewCell,在其 initWithFrame 中创建了一个 MyCustomViewClass 实例,然后将其添加到 contentView。性能提高了很多。谢谢!
    • @Eric 没问题 :)。如果您想在重用单元格后做某事,请不要忘记您有 prepareForReuse 。真的很方便。
    猜你喜欢
    • 1970-01-01
    • 2023-02-11
    • 1970-01-01
    • 2015-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-25
    相关资源
    最近更新 更多