skip to Main Content

I am new to swift, I followed this video to do a Collection view and it is working perfectly. But on clicking from one cell to another on clicking is not working.

https://www.youtube.com/watch?v=TQOhsyWUhwg

func collectionView(_ collectionView: UICollectionView, 
  didSelectItemAt indexPath: IndexPath) {
    print("Cell (indexPath.row + 1) clicked")
  }

Here it is printing the cell which is selected. I just need to open another view when the cell is clicked. Can anybody help me.

2

Answers


  1. You just need to create object of the another view controller and push it.
    like :

    let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
    let nextViewController = storyBoard.instantiateViewController(withIdentifier: "your_view_identifier") as! Your_ViewController
    self.navigationController?.pushViewController(nextViewController, animated: true)
    
    Login or Signup to reply.
  2. Let’s guess the viewController you want to navigate is SecondViewController. And Storyboard name is Main.

    To navigate a ViewController

    1. You need to create an instance of that ViewController
    2. You need to push that viewController from Navigation Controller
    class SecondViewController: UIViewController {
        
    }
    
    var secondViewController: SecondViewController {
        let st = UIStoryboard(name: "Main", bundle: nil)
        let vc = st.instantiateViewController(withIdentifier: "SecondViewController") as! SecondViewController
        return vc
    }
    

    Now if you want to navigate viewcontroller from cell tap. Just push that viewcontroller into your navigation stack.

    func collectionView(_ collectionView: UICollectionView, 
      didSelectItemAt indexPath: IndexPath) {
        print("Cell (indexPath.row + 1) clicked")
        self.navigationController?.pushViewController(secondViewController, animated: true)
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search