UICollectionView 单元格为零

UICollectionView cell is nil

我正在开发一个集合视图,其中填充了我在 Firebase 上的图像。一切正常,但是当我尝试执行 segue 时,我得到了这一行的 "unexpectedly found nil while unwrapping an Optional value":

if let indexPath = self.collectionView?.indexPath(for: sender as! UICollectionViewCell){}

我在 SO 中看到了许多工作示例,显然它们都适用于该行。

下面是相关代码的其余部分:

//grab Firebase objects in viewdidload and put them into productsArray

   var productsArray = [ProductsModel]()

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return productsArray.count
}



override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
    let imageView = cell.viewWithTag(1) as! UIImageView
    //imageView.image = imageArray[indexPath.row]

    let getUrl = productsArray[indexPath.row].productImg
    imageView.loadUsingCache(getUrl!)

    imageView.layer.borderColor = UIColor.lightGray.cgColor
    imageView.layer.borderWidth = 1
    imageView.layer.cornerRadius = 0

    return cell
}

    //NAVIGATION
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    performSegue(withIdentifier: "itemSegue", sender: nil)

}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if (segue.identifier == "itemSegue"){

        let destinationController = segue.destination as! ItemViewController

        if let indexPath = self.collectionView?.indexPath(for: sender as! UICollectionViewCell){
            destinationController.getProduct = productsArray[indexPath.row]
        }
    }
}

此外,我仔细检查了故事板中的所有连接和设置。

提前致谢!

在以下函数中,您将 sender 参数作为 nil 发送:

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    performSegue(withIdentifier: "itemSegue", sender: nil)
}

然后在下面的函数中,您接收到 sender 参数并尝试转换它 (sender as! UICollectionViewCell)。此参数将始终为零。

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if (segue.identifier == "itemSegue"){
        let destinationController = segue.destination as! ItemViewController
        if let indexPath = self.collectionView?.indexPath(for: sender as! UICollectionViewCell){
            destinationController.getProduct = productsArray[indexPath.row]
        }
    }
}

如果您不希望它为 nil,则不要使用 nil sender 调用 performSegue(withIdentifier:sender:) 函数。发送一个有效的对象。在这种情况下,您似乎希望 sender 的类型为 UICollectionViewCell。所以在 performSegue 函数中发送单元格。

编辑:Nirav D 很好地提到没有理由发送单元格,因为它无论如何都会转换回 indexPath。我们可以通过以下方式解决整个问题:

performSegue(withIdentifier: "itemSegue":, sender: indexPath)

和:

if let indexPath = sender as? IndexPath {
    destinationController.getProduct = productsArray[indexPath.row]
}