【问题标题】:Swift 3 - CollectionView select not visibleSwift 3 - CollectionView 选择不可见
【发布时间】:2023-04-01 11:54:02
【问题描述】:

每次我尝试选择一个不可见的单元格时,都会出现异常:

let cell = collectionView.cellForItem(at: indexPath) as! CustomCell

这就是为什么我决定先滚动到它,让它变得可见,然后选择它:

collectionView.scrollToItem(at: indexPath, at: [], animated: true)
let cell = collectionView.cellForItem(at: indexPath) as! CustomCell

但我仍然得到:

fatal error: unexpectedly found nil while unwrapping an Optional value

对于这一行:

let cell = collectionView.cellForItem(at: indexPath) as! CustomCell

有人可以帮我解决这个问题吗?

谢谢和问候!

【问题讨论】:

  • 既然cellForItem 被定义为对不可见的单元格返回nil,我不得不问,你为什么要选择一个? (我怀疑滚动问题是在事件循环运行之前 UI 不会更新,因此单元格没有机会变得可见......但我不确定。)
  • 为什么要首先选择一个不可见的单元格?
  • 我正在实现预选,而必须预选的单元格不可见...所以?
  • 尝试将单元格方法而不是单元格方法出列
  • 究竟是什么意思?

标签: swift uitableview exception scroll uicollectionview


【解决方案1】:

我们在 UICollectionViewDelegate 中做了 select 方法。

 func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
      //here you can access the cell 
      guard let cell = collectionView.cellForItem(at: indexPath) as? 
      CustomCell else { return }
      //write your code here
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多