如何通过Segue发送集合视图单元格文本

Ric*_*ard -1 xcode ios segue uicollectionview swift

我正在尝试将包含在收集视图单元格中的标签发送到带有segue的另一个视图控制器。

我的计划是,当用户点击集合视图单元格时,该应用程序会转到下一个视图控制器,在该视图控制器中,导航栏的标题将在所选集合视图单元格中显示标签的文本。

我已经试过了:

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

    //itemSelected = items[indexPath.row] as String

    itemSelected = cell.pLabel.text!

    print(itemSelected)
}
Run Code Online (Sandbox Code Playgroud)

在prepareForSegue中,由于不确定如何工作,因此我没有编写任何代码。

我注释掉了块“ ..items [indexPath.row] as String”,因为它不会显示标签,并添加了打印功能以查看将输出的内容,但仅输出情节提要中给出的名称。

我是Xcode的新手,所以对didSelect和prepareForSegue不熟悉。我要做的就是将带有收集的视图单元格中的文本发送到另一个视图控制器。

Bar*_*ğuz 7

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

        self.performSegue(withIdentifier: "contentVideoSegue", sender: indexPath)

}


override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if segue.identifier == "contentVideoSegue"{
        let selectedIndexPath = sender as? NSIndexPath
        let videoContentVC = segue.destination as! VideoContentController
        videoContentVC.text = items[selectedIndexPath.row] as String
    }
}
Run Code Online (Sandbox Code Playgroud)

希望能有所帮助:)


Nir*_*v D 6

从您的代码中,您没有调用 ,performSegue(withIdentifier:sender:)因此您可能已经创建了从 CollectionViewCell 到DestinationViewController. 因此,在prepareForSegue方法中使用此单元格获取 indexPath 。

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

     if let cell = sender as? UICollectionViewCell, 
        let indexPath = self.collectionView.indexPath(for: cell) {

         let vc = segue.destination as! SecondViewController //Cast with your DestinationController
         //Now simply set the title property of vc
         vc.title = items[indexPath.row] as String
     }
}
Run Code Online (Sandbox Code Playgroud)