Jarry Jarry - 28 days ago 7
iOS Question

How to open new view from collection view controller

I am new to iOS and struggling in opening new view controller from collection view.

Can anyone help me in how to open new view controller and pass date so i can change text of lable in another view.

Answer

For pushing a view controller from another view controller, you can use:

Method - 1. Create a segue in storyboard from FirstViewController to SecondViewController and use prepareForSegue method to pass data to SecondViewController

Here is how to do it:

Storyboard with FirstViewController and SecondViewController

enter image description here

  1. FirstViewController code:

    import UIKit

    class ViewController: UIViewController {
    override func viewDidLoad() { }

    @IBAction func onButtonTap(_ sender: UIButton)
    {
        self.performSegue(withIdentifier: "segue1", sender: self)
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?)
    {
        if segue.identifier == "segue1"
        {
            let secondVC = segue.destination as! SecondViewController
            secondVC.date = NSDate()
        }
    }
    

    }

  2. SecondViewController code:

    import UIKit

    class SecondViewController: UIViewController { var date : NSDate! @IBOutlet weak var dateLabel: UILabel!

    override func viewDidLoad()
    {
        super.viewDidLoad()
        self.dateLabel.text = date.description
    }
    

    }

Method - 2. Push the secondViewController programmatically using method:

Here is how to do it:

Don't create segue between FirstViewController and SecondViewController like in Method-1

  1. FirstViewController code:

    import UIKit

    class ViewController: UIViewController {
    override func viewDidLoad() { }

    @IBAction func onButtonTap(_ sender: UIButton)
    {
        let secondVC = self.storyboard?.instantiateViewController(withIdentifier: "SecondViewController") as! SecondViewController
        secondVC.date = NSDate()
    }
    

    }

  2. SecondViewController code: same as in Method-1