如何将数据数据从集合视图单元传递到视图控制器

时间:2018-11-09 11:46:51

标签: ios swift uicollectionviewcell swift4.2

我在collectionview单元格中有一个按钮,我正在尝试从视图控制器访问当前标题。

但是当我尝试访问时,我将标题作为默认标题“按钮”

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")
            }

        }

1 个答案:

答案 0 :(得分:3)

替换

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

使用

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

也是这个

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)
}

可以替换为

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