Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass Data using a pushViewController?

Using this code I am able to 'segue' to the same instance of my view controller

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let vc = storyboard.instantiateViewController(withIdentifier: "DetailVC")
    self.navigationController?.pushViewController(vc, animated: true)


}

However, how do I pass data over? I only know how to pass data using the segue option. When I run the code with this, I get nil errors because the new instantiated view controller cannot read the data.

like image 937
baxu Avatar asked Aug 23 '26 18:08

baxu


2 Answers

for example I add here, for detail description you can get the tutorial from here

class SecondViewController: UIViewController {

var myStringValue:String?

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    // We will simply print out the value here
    print("The value of myStringValue is: \(myStringValue!)")
}

and send the string as

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let vc = storyboard.instantiateViewController(withIdentifier: "DetailVC") as! SecondViewController
      vc.myStringValue = "yourvalue"

    self.navigationController?.pushViewController(vc, animated: true)


}
like image 88
Anbu.Karthik Avatar answered Aug 25 '26 10:08

Anbu.Karthik


First off. This isn't a segue. This is just pushing another view to the stack. And (like Ashley Mills says) this is not the same instance you are currently in. This is a NEW instance of a view controller.

But all you need to do is populate the data. You already have the controller here...

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    // you need to cast this next line to the type of VC.
    let vc = storyboard.instantiateViewController(withIdentifier: "DetailVC") as! DetailVC // or whatever it is
    // vc is the controller. Just put the properties in it.
    vc.thePropertyYouWantToSet = theValue

    self.navigationController?.pushViewController(vc, animated: true)
}

Then in your second view controller catch the value like this

class DetailVC: UIViewController {
    var thePropertyYouWantToSet = String()

    override func viewDidLoad() {
        print(thePropertyYouWantToSet)
    }
}
like image 32
Fogmeister Avatar answered Aug 25 '26 09:08

Fogmeister