gpt4 book ai didi

ios - UICollectionViewLayout.layoutAttributesForElementsInRect 的行为

转载 作者:行者123 更新时间:2023-12-01 16:06:33 25 4
gpt4 key购买 nike

我已经实现了我自己的从 UICollectionViewLayout 子类化的集合 View 布局。在 prepare我计算和缓存布局属性。
layoutAttributesForElementsInRect我过滤掉那些不正确的:

override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
return itemAttributesCache.filter { $0.frame.intersects(rect) }
}

我期望的数据源方法 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell将为 layoutAttributesForElementsInRect 中返回的每个索引路径调用

但是我发现如果我只是像这样返回整个属性集:
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
return itemAttributesCache
}
cellForItemAt方法仍然只为可见矩形内的属性调用。

这是预期的行为吗?如果是的话,在我的代码中过滤属性的目的是什么,如果集合 View 本身呢?我没有发现它有任何性能问题。

是否可以强制 collectionview 调用 cellForItemAt对于所有返回的属性?

最佳答案

是的,这是集合 View 的预期行为。在 UICollectionViewLayout 的文档中苹果说(强调):

The job of a layout object is to determine the placement of cells, supplementary views, and decoration views inside the collection view’s bounds and to report that information to the collection view when asked.



然后继续:

The collection view asks its layout object to provide layout information for these elements at many different times. Every cell and view that appears on screen is positioned using information from the layout object.



代码中过滤属性的目的是提高性能。影响布局对象性能的主要有三个因素:
  • 集合 View 数据源中的项目数。
  • 确定布局属性的复杂性。
  • 您的自定义布局属性所需的内存量。

  • 在上述条件不友好的情况下(你有很多项目,计算属性非常复杂,你的自定义属性需要大量内存)提前计算所有属性是不可行的,因为它会需要花费大量时间和资源来预先计算这些值,因此不要将它们缓存在 prepare 中。函数,你必须在 layoutAttributesForElementsInRect 中实现一些逻辑用于计算布局属性。在这种情况下,您使用可见的 rect 参数仅计算将在屏幕中可见的单元格和 View 的属性值。

    关于强制收藏 View 调用 cellForItemAt对于所有返回的属性,我不确定这样做的值(value)是什么,因为它只会使用其中的几个。实现这一目标的唯一方法是拥有一个与您正在显示的内容大小相同的集合 View ,以便所有单元格都被视为可见。但是,这样做首先使使用集合 View 的意义无效,因为单元格不会被重用,也不会滚动。如果你想用集合 View 项修复一些奇怪的动画,这不是要走的路。

    关于ios - UICollectionViewLayout.layoutAttributesForElementsInRect 的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59357522/

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