【问题标题】:How to push a navigation view using collectionView didSelectItemAt?如何使用 collectionView didSelectItemAt 推送导航视图?
【发布时间】:2020-01-13 23:20:06
【问题描述】:
我正在为我的学校项目编写代码。作为初学者,我在 youtube 上查找了如何编码的教程。
总结一下我使用的对象的层次结构:
主collectionView(第一个加载)用于在视图之间滚动horizontally。
列出collectionView 以列出单元格。
collectionViewCell 单元格用于列表信息。
但是,我无法找到一种方法,以便当我通过点击其中一个单元格来调用didSelectItemAt 函数来推送新的view 时。我尝试创建一个函数,将视图推送到 MainViewController 中,并通过在 didSelectItemAt 函数中创建 class 的实例来调用它,但我没有运气。
【问题讨论】:
标签:
ios
swift
uicollectionview
uicollectionviewflowlayout
【解决方案1】:
您是否添加了数据源和委托?如果您添加了,请检查单元格点击是否正常。如果点击工作添加波纹管导航代码。
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let controller = self.storyboard?.instantiateViewController(withIdentifier: "SecondViewController") as! SecondViewController
self.navigationController?.pushViewController(controller, animated: true)
}
【解决方案2】:
有助于 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)
}
}
【解决方案3】:
像这样添加上面的类:
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)
}