Ios 如何使用collectionView didSelectItemAt推送导航视图?

Ios 如何使用collectionView didSelectItemAt推送导航视图?,ios,swift,uicollectionview,uicollectionviewflowlayout,Ios,Swift,Uicollectionview,Uicollectionviewflowlayout,我正在为我的学校项目写代码。作为初学者,我在youtube上查阅了如何编写代码的教程。 要总结我使用的对象的层次结构,请执行以下操作: 主collectionView(加载的第一个视图),用于在视图之间水平滚动 列出列出单元格的列表collectionView collectionViewCell用于列表信息的单元格 但是,我找不到一种方法,当我调用时,点击其中一个单元格以推送一个新的视图来选择Itemat函数。我曾尝试创建一个函数,在MainViewController中推送视图,并通过在di

我正在为我的学校项目写代码。作为初学者,我在youtube上查阅了如何编写代码的教程。 要总结我使用的对象的层次结构,请执行以下操作:

collectionView
(加载的第一个视图),用于在视图之间水平滚动

列出列出单元格的列表
collectionView

collectionViewCell
用于列表信息的单元格


但是,我找不到一种方法,当我调用
时,点击其中一个单元格以推送一个新的
视图
来选择Itemat
函数。我曾尝试创建一个函数,在
MainViewController
中推送视图,并通过在
didSelectItemAt
函数中创建
class
的实例来调用它,但我没有成功。

是否添加了数据源和委托?。如果您添加了,请检查单元格单击是否工作。如果单击有效,请添加下面的导航代码

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 
    let controller = self.storyboard?.instantiateViewController(withIdentifier: "SecondViewController") as! SecondViewController
 self.navigationController?.pushViewController(controller, animated: true) 
    }

根据Raj的回答,如果您想在选择集合视图中的某个特定项目时按下视图控制器,只需稍微改变条件即可,单击集合视图中的某个项目即可调用此委托方法:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 
    if indexPath.item == **<your item's index>** {
        let controller = self.storyboard?.instantiateViewController(withIdentifier: "SecondViewController") as! SecondViewController
        self.navigationController?.pushViewController(controller, animated: true)
    }
}
func collectionView(collectionView:UICollectionView,didSelectItemAt indepath:indepath){

如果indexath.item==**将上侧添加到类中,如下所示:

    class tableViewVC : UIViewController, UITableViewDelegate, UITableViewDataSource {
}
添加内部ViewDidLoad():

然后您将在TableView中使用如下方法:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            let ViewController = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "SecondViewController") as? SecondViewController
            self.navigationController?.pushViewController(ViewController!, animated: true)
}

向我们显示您的代码。可能与
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            let ViewController = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "SecondViewController") as? SecondViewController
            self.navigationController?.pushViewController(ViewController!, animated: true)
}