单击 collectionView 单元格时如何打开不同的视图控制器

How to open different view controllers when a collectionView cell is click

我想知道如何在我的 collectionView 中单击特定单元格时打开不同的 viewController。对于这个例子,假设我有一个看起来像这样的 collectionView。

假装没有标签只是彩色视图。现在假设我的故事板中每个 collectionView 单元有 3 个不同的 viewController。故事板看起来像这样。

这就是我发现自己陷入困境的地方。因此,当单击橙色单元格时,我想显示橙色的 viewController ,反之亦然。我知道如何为所有单元格显示一个 viewController 而不是为特定单元格显示不同的 viewController。那么我将如何实现这一目标。非常感谢任何帮助或链接。感谢您花时间阅读我的问题。 :)

您需要使用不同的标识符来识别您点击的单元格。或者你可以使用单元格的颜色字符串

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let cell: UITableViewCell? = tableView.cellForRow(at: indexPath)
    if (cell?.reuseIdentifier == "red") {
        // go to red
    }
    else if (cell?.reuseIdentifier == "orage") {
        // go to orange
    }

}

您可以通过访问单元格背景的颜色 属性 轻松做到这一点。

override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    let cell: UITableViewCell? = tableView.cellForRow(at: indexPath)
    if (cell?.backgroundColor == .red) {
        // go to red
    }
    else if (cell?.backgroundColor == .orange) {
        // go to orange
    }

}