简体   繁体   中英

How can I passed data from collection view cell to new view controller (programmatically and without storyboard)?

I have problem about passing data from collection view cell to new view controller. I have collection view cells and each cell have image and labels and I want to create new view controllers for each cell.

I already tried to UINavigationController but present and navigationController codes not working under didSelectItemAt indexPath function. Everybody did this with storyboard but I didn't use it and I can't find solution.

    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)
}

Code had a error which is Value of type 'feedCell' has no member 'present' .

Try to inject dependencies to view controller in init method.

    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)
     }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM