Swift 3 - CollectionView 选择不可见

标签 swift uitableview exception scroll uicollectionview

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

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

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

谢谢和问候!

最佳答案

我们在 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
}

关于Swift 3 - CollectionView 选择不可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46689641/

相关文章:

swift - 在 SwiftUI View 中解包可选

iOS 模拟器不显示完整的应用程序

ios - 在 SWIFT 中推送之前如何加载 View ?

java - java中未报告的异常处理

ios - xcode 中性能测试的单独方案

iphone - 如何将选定的 UITableViewController 值添加到以前的 UITableViewController?

ios - Swift,Identing Table Views 每行缩进更多

node.js - 无法捕获 Node opencv 错误?

动态生成类的 Ruby 异常继承

arrays - 数组名称被描述为字符串