Home > Blockchain >  Opening another viewcontroller when clicking on cell of collectionview
Opening another viewcontroller when clicking on cell of collectionview

Time:09-16

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.

CodePudding user response:

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)

CodePudding user response:

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