gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 15:16:46 26 4
gpt4 key购买 nike

为什么在索引路径处的 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com