0

I am trying to figure out how to successfully pass data when a collection view cell is selected, to another view controller through segue. When I select a cell I get a crash. I have not segued with a collection view before. Am I correctly preparing the segue before I preform it? I am getting a crash when I select a cell. My data is returning nil. If I push the view controller it works fine.

// Root view controller, contains collection view that holds different categories. When cell is selected, it should take user to n
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        if segue.identifier == "pushToPosts" {

        let vc = segue.destination as? ExplorePostsVC
        if let cell = sender as? UICollectionViewCell, let indexPath = collectionView.indexPath(for: cell) {
        switch selectedSegmentIndex {
            case 0: vc?.style = femaleStyles[indexPath.row]
            case 1: vc?.style = maleStyles[indexPath.row]
                default: break

                }

            }

    }


    }


func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
 self.performSegue(withIdentifier: "pushToPosts", sender: self)

    }

When I select a cell, I get a Fatal error. All of the data is returning nil in the next view controller.


// ExplorePostsVC

 // To pass images and label
    var styleName = ""
    var styleDetails = ""
    var styleImage: UIImage?
    var style: Style!
    var headerView: ExplorePostHeader?
    override func viewDidLoad() {
    super.viewDidLoad()

fetchPosts()
    navigationController?.navigationBar.prefersLargeTitles = false
    navigationController?.navigationItem.largeTitleDisplayMode = .never
    collectionView.delegate = self
    collectionView.dataSource = self


    }

// Fetch posts based on selected cell

    func fetchPosts() {


 self.styleDetails = style.details //Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
 self.styleName = style.name
 switch style.gender {

        case.female:

        FEMALE_STYLES_REF.child((style.childValue)).observe(.childAdded) { (snapshot) in
        let postId = snapshot.key
        Database.fetchPost(with: postId, completion: { (post) in
        self.posts.append(post)
        self.posts.sort(by: { (post1, post2) -> Bool in
        return post1.creationDate > post2.creationDate

        })

        self.collectionView?.reloadData()


                })

            }


        case .male:

        MALE_STYLES_REF.child((style.childValue)).observe(.childAdded) { (snapshot) in
        let postId = snapshot.key
        Database.fetchPost(with: postId, completion: { (post) in
        self.posts.append(post)
        self.posts.sort(by: { (post1, post2) -> Bool in
        return post1.creationDate > post2.creationDate
        })
        self.collectionView?.reloadData()

        })

            }

        }
  }

Clint
  • 387
  • 5
  • 25
  • 2
    `print(sender)`. Is it the cell? In such a case it's better to force unwrap `sender` and `destination` to find the issue immediately. If everything is hooked up correctly the code must not crash. – vadian Apr 09 '20 at 04:46
  • @vadian Your comment helped me get to where I need to be, and I found that some code was not hooked up correctly not included in the question. ```style``` needed code clean up so thank you! – Clint Apr 10 '20 at 00:11

1 Answers1

0

You should use something like this in your didSelectItemAt method

func collectionView(_ collectionView: UICollectionView, didSelectItemAt 
indexPath: IndexPath) {

    if let cell = collectionView.cellForItem(at: indexPath) {
        self.performSegue(withIdentifier: "pushToPosts", sender: cell)
    }
}
  • If the segue is connected to the collection view **cell** (rather than to the view controller) the code in the question is supposed to work – vadian Apr 09 '20 at 07:37