ios - CollectionView dequeCell 从单元格中删除 subview 使 View 显得缓慢

标签 ios objective-c

我有代码:

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

    return 30;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

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

    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:REUSE_IDENTIFIER forIndexPath:indexPath];
    [[cell subviews]
     makeObjectsPerformSelector:@selector(removeFromSuperview)];
     [cell addSubview:someView];
    return cell;
}
  • 以上代码在viewWillAppear中执行
  • 如果我让上面的代码执行 30 次, View 外观真的很慢。

  • 由于单元格重用,我需要调用 removeFromSuperView。否则陈旧的错误数据会显示在单元格上。

我无法弄清楚是什么导致了缓慢??

你能提供提示吗?

最佳答案

您的外观很慢,因为您正在遍历单元格中的所有 subview 并从父 View 中移除。这是一个非常昂贵的过程,不应该在 collectionView 数据源的 cellForItemAtIndexPath 方法中完成/事实上,永远不应该这样做。如果需要显示相关内容,则需要访问单元格的实例并更新单元格内 UI 元素的属性。

关于ios - CollectionView dequeCell 从单元格中删除 subview 使 View 显得缓慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31041737/

相关文章:

ios - React Native : Building for IOS failed on XCode 9. 2 和 9.4 以及 RN 55.4

ios - Realm Swift iOS - 安全地删除和重新键入加密的 Realm

ios - 正确设置 numberOfRowsInSection

ios - UITableViewCell 子类在重新显示时重新加载 subview

iphone - 屏蔽 UIView 的特定 subview ?

iphone - 如何检测我的 UITextView 何时被编辑然后调用操作?

ios - 如何使 UILabel 中的文本环绕特定字符?

iOS 电源键,是否可以判断触摸事件?

objective-c - 如何在 osx 中的 NSDatePicker 对象上设置当前日期

ios - SpriteKit 游戏中的多任务问题