Search code examples
iosswiftuicollectionviewpushviewcontroller

how to pass data from cell to another ViewController


@TusharMordiya Please check this image I have created a tableView inside a CollectionView.The contents of the view are UIImage and a UILabel.I want to design the cell in which when I click on a cell the image and label must go to another ViewController.

import UIKit

class ExploreTableViewCell: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{

   @IBOutlet var collectionView: UICollectionView!

   var namearr = ["images-1", "images-2", "images-3", "images-4", "images-5"]

   override func awakeFromNib() {
      super.awakeFromNib()
    
      collectionView.delegate = self
      collectionView.dataSource = self

   }
   override func setSelected(_ selected: Bool, animated: Bool) {
      super.setSelected(selected, animated: animated)

   }

   func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
      return 10
   }



   func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
      let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
      return cell
   }

   func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
      return CGSize(width: 132, height: 134)
   }


   func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    
      let vc = UIStoryboard(name: "DetailViewController", bundle: nil).instantiateViewController(withIdentifier:"DetailViewController") as? DetailViewController
    
      vc?.name = namearr[indexPath.row]
      vc?.img.image = UIImage(named: namearr[indexPath.row])
      //self.navigationController?.pushViewController(vc, animated: true)
    
      // showing error in here and while declaring object of viewcontroller
   }
}

Solution

  • Please try this.

    1. Add function for get top most view controller

      extension UIApplication {
      
           class func topViewController(_ viewController: UIViewController? = UIApplication.shared.connectedScenes
                                   .filter({$0.activationState == .foregroundActive})
                                   .compactMap({$0 as? UIWindowScene})
                                   .first?.windows
                                   .filter({$0.isKeyWindow}).first?.rootViewController) -> UIViewController? {
               if let nav = viewController as? UINavigationController {
                   return topViewController(nav.visibleViewController)
               }
               if let tab = viewController as? UITabBarController {
                   if let selected = tab.selectedViewController {
                       return topViewController(selected)
                   }
               }
               if let presented = viewController?.presentedViewController {
                   return topViewController(presented)
               }
               return viewController
           }
       }
      
    2. Use this code in your didSelectItemAt method

      func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
      
          let storyBoard = UIStoryboard(name: "Main", bundle: nil)
          if let vc = storyBoard.instantiateViewController(withIdentifier:"DetailViewController") as? DetailViewController {
      
            vc.name = namearr[indexPath.row]
            print("You tapped the cell\(indexPath) with car name \(namearr[indexPath.row]) ")
            UIApplication.topViewController()?.navigationController?.pushViewController(vc, animated: true)
          }
      }
      
    3. In your Detail Screen

      class DetailViewController: UIViewController {
      
         @IBOutlet var lbl: UILabel!
         @IBOutlet var img: UIImageView!
      
         var name = ""
      
      
         override func viewDidLoad() {
             super.viewDidLoad()
             lbl.text = name
             img.image = UIImage(named: name)
      
         }
      }