alex00x0
alex00x0

Reputation: 27

Passing data with override func prepare using collectionviewCell

I am trying to send the charName String from AvengersViewController to CharViewController.

I am using a collection view in AvengersViewController. CharName is a label in CharViewController.

What I am trying works perfectly with a table view but I can't get it to work using collectionViews...

I am using "lastItemSelectedA" to indicate the index of the label from my avengers array. The passing of data works... I can't get the index of the collectionViewItem to pass with the first segue, thus, making it null. By using the default value of 0 I have been able to notice that it does work, however, it does not change the value of lastItemSelectedA when the cell is pressed but after... Or at least it does not update the variable.

I have already tried at least 5 implementations from solutions on stack.

extension AvengersViewController: UICollectionViewDelegate, UICollectionViewDataSource {

 func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        lastItemSelectedA = indexPath.item
        //self.performSegue(withIdentifier: "openToCharA", sender: indexPath.item)
    }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        guard let identifier = segue.identifier else { return }

        switch identifier {
        case "openToCharA":


            if let destination = segue.destination as? CharViewController {
                destination.charName = avengers[lastItemSelectedA ?? 0].name
            }

            //destination.sounds = sounds
            //guard let indexPath = collectionView.indexPathsForSelectedItems else {return}
            //let sounds = fallen[lastItemSelectedF!].sounds

        default:
            print("unexpected segue identifier")
        }
}

Upvotes: 0

Views: 309

Answers (1)

vadian
vadian

Reputation: 285150

If prepare(for segue is called then you've connected the segue from the collection view cell (rather than from the controller).

In this case delete

var lastItemSelectedA : Int

and

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    lastItemSelectedA = indexPath.item
    //self.performSegue(withIdentifier: "openToCharA", sender: indexPath.item)
}

and get the index path of the collection view cell from the sender parameter

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "openToCharA" {
        let cell = sender as! UICollectionViewCell
        let indexPath = collectionView.indexPath(for: cell)!
        let destination = segue.destination as! CharViewController
        destination.charName = avengers[indexPath.item].name
    }
}

Force unwrapping the optionals is fine in this case. The code must not crash if everything is hooked up correctly and if it does it reveals a design mistake.

Upvotes: 1

Related Questions