UICollectionView单元格为零

时间:2017-01-24 18:36:25

标签: swift null collectionview

我正在处理一个集合视图,其中包含我在Firebase上拥有的图像。一切正常,但是当我尝试执行segue时,我在这行中得到“意外发现nil,同时展开一个Optional值”:

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]
        }
    }
}

另外,我仔细检查了所有连接并在故事板中设置的内容。

提前致谢!

1 个答案:

答案 0 :(得分:1)

在以下函数中,您将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]
        }
    }
}

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

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

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

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