Search code examples
iosswiftsegueuicollectionviewcelluistoryboardsegue

Swift 3 Segue from UICollectionView Cell


Hi I'm a beginner and stuck on a very basic segue! I just want to find out the correct syntax to use for the sender e.g sandals[indexPath.row]sandalName Thanks

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! shoeCollectionViewCell
    let sandalCell = sandals[indexPath.row]
    cell.sandalImage.image = UIImage(named: sandalCell["image"]!)
    cell.sandalStyleName.text = sandalCell["styleName"]
    cell.sandalPrice.text = sandalCell["price"]
    return cell
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "shoeDetailSegue"{
        var detailPage = segue.destination as! shoeDetailViewController
        let selectedCell = sender as! UICollectionViewCell
        let indexPath = collectionView?.indexPath(for: cell)
        detailPage.getName = sandals[indexPath!.row].sandalName
        detailPage.getPrice = sandals[indexPath!.row].sandalPrice
        detailPage.getImage = sandals[indexPath!.row].sandalImage
    }
}

Solution

  • If you want to just pass the value with segue you need to simply access the array with subscript same way you are doing in cellForItemAt.

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "shoeDetailSegue"{
    
            var detailPage = segue.destination as! shoeDetailViewController
            let selectedCell = sender as! UICollectionViewCell
            let indexPath = collectionView?.indexPath(for: cell)
            let sandal = sandals[indexPath!.row]
            detailPage.getName = sandal["styleName"]!
            detailPage.getPrice = sandal["price"]!
            detailPage.getImage = UIImage(named: sandal["image"]!)
        }
    }