-4

I am writing a code for my school project. As a beginner would, I looked up on tutorials on youtube how to code. To summarize the hierarchy of my used objects:

Main collectionView (first one loaded) for scrolling horizontally between views.

List collectionView for listing cells.

collectionViewCell cells for listing information.

However, I am unable to find a way so that when I call a didSelectItemAt function by tapping on one of the cells to push a new view. I have tried creating a function that pushes the view in the MainViewController and call it by creating an instance of the class in didSelectItemAt function but I had no luck.

Jakir Hossain
  • 3,830
  • 1
  • 15
  • 29
Nojus
  • 21
  • 2

3 Answers3

0

have you added datasource and delegate?. if you added please check cell click working or not. if click is working add bellow navigation code.

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 
    let controller = self.storyboard?.instantiateViewController(withIdentifier: "SecondViewController") as! SecondViewController
 self.navigationController?.pushViewController(controller, animated: true) 
    }
Raj
  • 485
  • 9
  • 18
0

Contributing to Raj's answer, if you want to push a view controller when selecting some specific item in your collection view, just a slight variation of condition will do the trick, this delegate method is called with you click on an item in your collection view:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 
    if indexPath.item == **<your item's index>** {
        let controller = self.storyboard?.instantiateViewController(withIdentifier: "SecondViewController") as! SecondViewController
        self.navigationController?.pushViewController(controller, animated: true)
    }
}
Mumtaz Hussain
  • 925
  • 9
  • 23
0

Add the upper Side the Class like this :

    class tableViewVC : UIViewController, UITableViewDelegate, UITableViewDataSource {
}

Add inside ViewDidLoad():

tableView.delegate = self
  tableView.datasource = self

And then you will use in TableView Method like this :

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            let ViewController = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "SecondViewController") as? SecondViewController
            self.navigationController?.pushViewController(ViewController!, animated: true)
}