首页 > 解决方案 > 如何将数据从集合视图单元传递到新的视图控制器(以编程方式且没有情节提要)?

问题描述

我在将数据从集合视图单元传递到新视图控制器时遇到问题。我有集合视图单元格,每个单元格都有图像和标签,我想为每个单元格创建新的视图控制器。

我已经尝试过 UINavigationController 但现在和 navigationController 代码在 didSelectItemAt indexPath 函数下不起作用。每个人都用故事板做这个,但我没有使用它,我找不到解决方案。

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    print("#\(indexPath.item)!")
    //let cell = collectionView.cellForItem(at: indexPath) as! itemsCell
    //let cell = itemler[indexPath.row]

    let newView = UINavigationController(rootViewController: orderBasketController())
    self.present(newView, animated: true, completion: nil)
}

代码有一个错误,即Value of type 'feedCell' has no member 'present'

标签: iosswiftxcodeuicollectionviewcell

解决方案


尝试在init方法中注入依赖项以查看控制器。

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        guard let yourCell = collectionView.cellForItem(at: indexPath) as? YourCellClass else {
            return
        }
        let yourModel = Model(title: yourCell.title, image: yourCell.image)
        let targetViewController = TargetViewController(model: yourModel)
        navigationController?.pushViewController(targetViewController, animated: true)
        // or if it's not in navigation controller
        // present(targetViewController, animated: true, completion: nil)
     }

推荐阅读