ios - 为什么 UICollectionView cellForItemat indexpath 会在一开始就为所有单元格调用

标签 ios swift uitableview uicollectionview uicollectionviewcell

为什么在索引路径处的 UICollectionView 的 cellForItem 在显示之前被调用所有单元格。 collectionView 不应该只获取它需要的单元格吗……即将像 tableview 一样显示在屏幕上的单元格?

步骤

  • 带有 ViewController 的 Storyboard。 ViewController 有 CollectionView。 CollectionView 具有垂直流布局。

  • ViewController 有 collectionView 的 IBOutlet 并实现了 collectionView 的数据源和委托(delegate)方法

  • 在数据源和委托(delegate)方法中,单元格(为其大小使用自动布局)被传递到 collectionview .. 索引路径中项目的单元格

在传递单元格之前放置打印语句,表明在屏幕上显示 Collection View 之前请求了所有单元格。

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var collectionView: UICollectionView!

    override func viewDidLoad() {
        super.viewDidLoad()

        var flowLayout=collectionView.collectionViewLayout as! UICollectionViewFlowLayout;
        flowLayout.estimatedItemSize = CGSize(width:20,height:30);
        self.collectionView.register(UINib(nibName:"ShortCell", bundle:nil), forCellWithReuseIdentifier: "ShortCell");
        self.collectionView.register(UINib(nibName:"LongCell", bundle:nil), forCellWithReuseIdentifier: "LongCell");
    }
}

extension ViewController:UICollectionViewDelegate,UICollectionViewDataSource{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 500;
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let row=indexPath.row;
        print("row:",indexPath.row);
        let rem = row % 2;
        if(rem==0){
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ShortCell", for: indexPath);
            return cell;
        }
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "LongCell", for: indexPath);
        return cell;
    }
}

为什么collectionview在显示之前需要获取所有的cell?为什么它不像 tableview 那样只以零碎的方式请求单元格?这是一个问题吗?

最佳答案

经过一些调查......

当使用 flowLayout.estimatedItemSize 时,自动布局会进行一次布局传递以计算在该估计大小 适合多少单元格,忽略实际单元格内的任何自动调整大小。

因此,如果您将 .estimatedItemSize 更改为实际的估计大小,您应该只获得(大约)调用 cellForItemAt 的次数根据需要。

请注意不要高估大小。如果你这样做,你要么得到一大堆

The behavior of the UICollectionViewFlowLayout is not defined because: the item width must be less than the width of the UICollectionView minus the section insets left and right values, minus the content insets left and right values.

错误消息,或者你得到愚蠢的(不准确的)大小的滚动指示器。

关于ios - 为什么 UICollectionView cellForItemat indexpath 会在一开始就为所有单元格调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46714019/

相关文章:

ios - 自定义 UITableViewController 结构

ios - 如何在不单击通知 ios 的情况下在接收本地通知时自动启动应用程序

IOS 钥匙串(keychain)服务

ios - 在 SwiftUI 中,如何访问 UIViewRepresentable 中 .foregroundColor 和其他修饰符的当前值?

iphone - 在具有安全文本输入的 UITextField 上忽略 UIKeyboardTypeNumbersAndPunctuation

swift - uitableViewCell 错误的背景颜色

iphone - NSMutableArray 没有正确添加对象?

iphone - Icenium 未找到配置文件

ios - Xcode 11 : How to stack editor vertically?

ios - 无法将 View Controller 连接到 Swift 文件