【发布时间】:2021-04-01 09:28:25
【问题描述】:
我有一个动态集合视图。如何通过单击集合视图的单元格从一个视图控制器移动到另一个视图控制器? 提前谢谢你
【问题讨论】:
我有一个动态集合视图。如何通过单击集合视图的单元格从一个视图控制器移动到另一个视图控制器? 提前谢谢你
【问题讨论】:
collectionview有一个委托方法didselect可以使用
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// write code to go from one viewcontroller to another
}
【讨论】:
确保您已将 collectionView 授予委托。请参阅下文如何设置委托。
override func viewDidLoad() {
super.viewDidLoad()
collectionvVew.delegate = self
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// Write your navigation controller name instead of **ViewController**
let vc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "ViewController") as? ViewController
self.navigationController?.pushViewController(vc!, animated: true)
}
我已经分享了我的答案。如果我对您的问题的理解有误,请告诉我。
【讨论】:
尝试将手势识别器(在您的 cellForItemAt 函数中)添加到单元格 contentView 并以编程方式调用您的目标控制器:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "yourCellId", for: indexPath) as! yourCell
let gesture = UITapGestureRecognizer(target: self, action: #selector(changeVc))
cell.contentView.addGestureRecognizer(gesture)
return cell
}
或者您可以像这样向 imageView 单元格添加手势:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! yourCollecctionViewCell
let gesture = UITapGestureRecognizer(target: self, action: #selector(changeVc))
cell.yourImageView.isUserInteractionEnabled = true // don't forget to enable user interaction in your image view
cell.yourImageView.addGestureRecognizer(gesture)
return cell
}
现在编写改变VC的函数:
@objc fileprivate func changeVc() {
let vc = YourDestinationController()
vc.modalPresentationStyle = .fullScreen // if you don't want full screen comment this line,
present(vc, animated: true, completion: nil)
}
在导航控制器的情况下:
@objc fileprivate func changeVc() {
let vc = YourdestinationController()
navigationController?.pushViewController(vc, animated: true)
}
【讨论】: