gpt4 book ai didi

iOS( swift ): Collection View indexPath(for: cell) is nil for non visible cell

转载 作者:行者123 更新时间:2023-11-28 10:08:23 27 4
gpt4 key购买 nike

我有一个 UIViewController,它使用 Object 类型的数组填充 UICollectionView:

class MyViewController: UIViewController {

let objects: [Object]!

weak var collectionView: UICollectionView!

func object(for cell: MyCell) {
guard let indexPath = self.collectionView.indexPath(for: cell) else { fatalError("No cell at index path") }
}

}

collectionView 单元格表示为:

class MyCell: UICollectionViewCell {

weak var delegate: MyCellDelegate?

override func apply(_ layoutAttributes: UICollectionViewLayoutAttributes) {
super.apply(layoutAttributes)

let obj = self.delegate?.object(for: self)
// configure various subviews with obj ...

}
}

它有一个 delegateMyViewController 对话以获取表示的 Object 实例:

protocol MyCellDelegate: class {
func object(for cell: MyCell) -> Object
}

当我在单元格之间向下滚动时这工作正常但是,它在 guard let indexPath = self.collectionView.indexPath(for: cell) ... 崩溃apply(_ layoutAttributes: UICollectionViewLayoutAttributes) 方法被调用。

有办法解决这个问题吗?单元格需要知道它们代表的是哪个 Object 实例,以便 View Controller 可以调整模型。

非常感谢您的帮助!

最佳答案

总是假设如果一个单元格在屏幕外,那么 Collection View 已经回收了它。 Collection View 不断执行此操作以保持低内存使用率和高性能。

为了在屏幕外执行一些操作,我经常做的是持有一个单独的对象( View 模型,在 MVVM 中),可见单元格可以附加到该对象上。该对象由我的对象拥有和保留,并且永远不会被回收。如果我需要执行任何屏幕外操作,此对象会执行。

细胞的唯一工作是:

  1. 显示数据和
  2. 接收用户输入

这两者都要求它是可见的。

当我创建单元格时,我使用 prepareForReuse 将其与之前的 View 模型分离,并在将单元格附加到下一个 View 模型之前进行必要的清理。

替代解决方案

如果您只需要索引路径来获取您的特殊对象,您可以简单地使用布局属性中的索引路径。

protocol MyCellDelegate: class {
func object(for indexPath: IndexPath) -> Object
}

class MyCell: UICollectionViewCell {

weak var delegate: MyCellDelegate?

override func apply(_ layoutAttributes: UICollectionViewLayoutAttributes) {
super.apply(layoutAttributes)

let obj = self.delegate?.object(for: layoutAttributes.indexPath)
// configure various subviews with obj ...

}
}

关于iOS( swift ): Collection View indexPath(for: cell) is nil for non visible cell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50744293/

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