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

时间:2019-09-12 06:07:03

标签: ios swift uicollectionview uicollectionviewflowlayout

我正在为我的学校项目编写代码。作为初学者,我在youtube上学习了如何编码的教程。 总结我使用过的对象的层次结构:

主要collectionView(已加载第一个),用于在视图之间滚动horizontally

列出collectionView列出单元格。

collectionViewCell单元格用于列出信息。

但是,我无法找到一种方法,当我通过点击其中一个单元格来推送新的didSelectItemAt来调用view函数时。我尝试创建一个函数,该函数可以在MainViewController中推送视图,并通过在class函数中创建didSelectItemAt的实例来调用它,但是我没有运气。

3 个答案:

答案 0 :(得分:0)

您是否添加了数据源和委托?如果添加了,请检查单元格单击是否正常。如果单击有效,则添加以下导航代码。

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

答案 1 :(得分:0)

有助于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)
    }
}

答案 2 :(得分:0)

像上面这样添加Class类:

    class tableViewVC : UIViewController, UITableViewDelegate, UITableViewDataSource {
}

在ViewDidLoad()中添加:

tableView.delegate = self
  tableView.datasource = self

然后您将在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)
}