繁体   English   中英

iOS(Swift):对于不可见的单元格,集合视图indexPath(for:cell)为nil

[英]iOS (Swift): Collection View indexPath(for: cell) is nil for non visible cell

我有一个UIViewControllerUICollectionView使用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 ...

    }
}

它有一个与MyViewController对话以获取表示以下内容的Object实例的delegate

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

当我在单元格之间向下滚动时,此方法可以正常工作,但是,当调用apply(_ layoutAttributes: UICollectionViewLayoutAttributes)方法时,对于不在屏幕上的guard let indexPath = self.collectionView.indexPath(for: cell) ... ,它会在guard let indexPath = self.collectionView.indexPath(for: cell) ...崩溃guard let indexPath = self.collectionView.indexPath(for: cell) ...

有没有办法解决这个问题? 单元需要知道它们代表的是哪个Object实例,以便视图控制器可以调整模型。

非常感谢您的帮助!

始终假定如果某个单元格不在屏幕上,则说明该集合视图已经对其进行了回收。 收集视图会不断这样做,以保持较低的内存使用量和较高的性能。

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

该单元的唯一任务是:

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

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

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

替代解决方案

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

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 ...

    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM