2017-01-24 11 views
0

Я работаю над представлением коллекции, которое заполняется изображениями, которые у меня есть на Firebase. Все работает отлично, но когда я пытаюсь выполнить SEGUE я получаю «неожиданно нашел ноль, а разворачивание необязательного значения» для этой линии:UICollectionView cell is nil

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

В следующей функции, вы отправляете параметр 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:) с nilsender. Отправьте действительный объект. В этом случае, кажется, вы хотите, чтобы 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' вместо ячейки. –