免责声明:显然我的示例非常简化,因为您没有发布任何代码。请考虑下次这样做,因为如果您这样做,其他人可以更好地帮助您。
首先你必须创建一个从第一个到第二个 ViewController 的 Segue。您可以通过使用鼠标右键从 (1) 拖动到 (2) 来执行此操作(为了测试,我使用了 UITableView,但整个过程应该使用 CollectionView 相同)。
然后从上下文菜单中选择Show。
现在你应该有一个箭头,从第一个 ViewController 指向第二个 ViewController。选择它并在右侧的属性检查器中为其指定一个唯一标识符。
现在您可以进入第一个 ViewController 的代码并将以下代码添加到 didSelectItemAt 函数(显然将 <YOUR IDENTIFIER> 替换为您之前提供给 segue 的实际标识符)。
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
self.performSegue(withIdentifier: "<YOUR IDENTIFIER>", sender: collectionView.cellForItem(at: indexPath))
collectionView.deselectItem(at: indexPath, animated: true)
}
现在,如果您选择一个单元格,您将转到第二个 ViewController,但 NavigationController 保持不变。您甚至可以免费获得一个后退按钮。
如果你需要给第二个 ViewController 一些关于哪个 Cell 被按下的信息,你必须做更多的事情。
假设,您需要所选单元格的 IndexPath,并且您的第二个 ViewController 的 ViewController 文件如下所示:
import UIKit
class ViewController2: ViewController {
@IBOutlet weak var label: UILabel!
var indexPath: IndexPath!
override func viewDidLoad() {
super.viewDidLoad()
label.text = "\(self.indexPath.row)"
}
}
现在您需要一种将 IndexPath 提供给第二个 ViewController 的方法。
你可以这样做,使用prepare(for:sender:) 函数,如下所示:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "<YOUR IDENTIFIER>", let dest = segue.destination as? ViewController2, let cell = sender as? UICollectionViewCell {
dest.indexPath = self.collectionView.indexPath(for: cell)!
}
}