2017-01-24 152 views
0

我正在使用Firebase上的图像填充集合视图。一切工作正常,但是当我尝试执行赛格瑞我得到“意外发现零而展开的可选价值”这条线:UICollectionView单元格为零

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

我在所以在这里看到了很多工作的例子,显然他们都很好地工作那条线。

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

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

在下面的功能,您发送的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] 
     } 
    } 
} 

如果你不希望它是零,那么不要用nilsender调用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] 
} 
+0

感谢解释,无法相信我错过了。 – Noah

+0

没有不发送单元作为发件人,你想indexPath,所以只需发送indexPath作为发件人。 –

+0

@ Noah1尼拉夫说得很好。既然你正在寻找'indexPath',只需将'indexPath'作为'sender'而不是单元格。 –