Aditya A.Rajan
Aditya A.Rajan

Reputation: 549

how to pass data data from collection view cell to view controller

I have a button in collectionview cell and i am trying to access the current title from the view controller.

But when I try to access, I get the title as the default title "Button"

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
             let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "graphCell", for: indexPath) as! graphCell


             let row = indexPath.row

            if row == 0{
                print("Compare")
            }

            else if row == 1{
                let optSelected=cell.chooseBTN.title(for: .normal)
                print(option)
                if optSelected=="Sales"{
                    let storyboard = UIStoryboard(name: "Main", bundle: nil)

                    let vc = storyboard.instantiateViewController(withIdentifier: "SalesVC") as! SalesVC

                    vc.buttonClicked = "Sales"; navigationController?.pushViewController(vc, animated: true)
                }
                else if optSelected=="Collection"{
                    let storyboard = UIStoryboard(name: "Main", bundle: nil)

                    let vc = storyboard.instantiateViewController(withIdentifier: "SalesVC") as! SalesVC

                    vc.buttonClicked = "Collection"; navigationController?.pushViewController(vc, animated: true)

                }

            }

            else if row == 2{
                print("PRO-wise")
            }
            else if row == 3{
                print("TAT")
            }

        }

Upvotes: 1

Views: 1464

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100503

Replace

 let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "graphCell", for: indexPath) as! graphCell

with

 let cell = collectionView.cellForItem(at:indexPath) as! graphCell

also this

let optSelected=cell.chooseBTN.title(for: .normal)
print(option)
if optSelected=="Sales"{
    let storyboard = UIStoryboard(name: "Main", bundle: nil)

    let vc = storyboard.instantiateViewController(withIdentifier: "SalesVC") as! SalesVC

    vc.buttonClicked = "Sales"; navigationController?.pushViewController(vc, animated: true)
}
else if optSelected=="Collection"{
    let storyboard = UIStoryboard(name: "Main", bundle: nil)

    let vc = storyboard.instantiateViewController(withIdentifier: "SalesVC") as! SalesVC

    vc.buttonClicked = "Collection"; navigationController?.pushViewController(vc, animated: true)
}

can be replaced with

  let vc =  storyboard.instantiateViewController(withIdentifier: "SalesVC") as! SalesVC
  vc.buttonClicked = cell.chooseBTN.title(for: .normal)
  navigationController?.pushViewController(vc, animated: true)

Upvotes: 3

Related Questions