Swift中点击UICollectionView的cell如何打开另一个ViewController
实现UICollectionView点击cell跳转页面的方案
前置准备
- 先创建你要跳转的目标页面对应的
UIViewController子类,比如命名为DetailViewController - 若使用Storyboard搭建目标页面,需要在Storyboard的属性检查器中给目标ViewController设置Storyboard ID,建议和类名保持一致比如
DetailViewController,同时勾选「Use Storyboard ID」选项
常用实现方式
方式1:导航控制器push跳转(页面左边缘可右滑返回,适合层级导航场景)
在你现有的didSelectItemAt方法中补充如下代码:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { print("Cell \(indexPath.row + 1) clicked") // 初始化目标ViewController,纯代码写法如下 let detailVC = DetailViewController() // 如果是Storyboard创建的目标VC,替换为下面的写法 // let detailVC = storyboard?.instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController // 可选:给目标VC传值,比如把当前点击的cell对应的数据传给下一页 // detailVC.receivedData = yourDataSourceArray[indexPath.row] // 执行push跳转 navigationController?.pushViewController(detailVC, animated: true) }
注意:该方式生效的前提是当前的ViewController已经被包裹在
UINavigationController中
方式2:模态弹出跳转(从底部向上弹出页面,适合临时操作场景)
仅需把跳转代码替换为modal相关实现即可:
// 模态弹出 present(detailVC, animated: true) // 如果需要自定义弹出样式,可以加如下配置 // detailVC.modalPresentationStyle = .fullScreen
方式3:Storyboard Segue跳转
如果你的项目完全使用Storyboard做页面跳转,直接在Storyboard中从cell拖拽Segue到目标ViewController,设置Segue的标识符比如showDetailSegue,然后实现如下方法即可:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showDetailSegue", let indexPath = collectionView.indexPathsForSelectedItems?.first, let detailVC = segue.destination as? DetailViewController { // 传值逻辑 detailVC.receivedData = yourDataSourceArray[indexPath.row] } }
内容的提问来源于stack exchange,提问作者roshanpeter
相关产品推荐
相关产品推荐

