Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Xcode: instantiating a view controller with custom variable

So I want to instantiate a view controller from storyboard and change it’s static variables…

this is "vc1" – the view controller to be instantiated:

import UIKit

class vc1: UIViewController {
    @IBOutlet weak var lbl_title: UILabel!
    
    static var title = "initial value"
    
    override func viewDidLoad() {
        super.viewDidLoad()

        lbl_title.text = vc1.title
    }
}

And this is my root vc…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var btn_go: UIButton!
    
    @IBAction func btn_gogogo(_ sender: Any) {
        
        let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "vc1") as! vc1
        
        vc.title = "bla"

        self.present(vc, animated: true, completion: nil)
    }

}

here I’m trying to change the static variable of the view controller that I just instantiated…
with no effect… the variable ( in my case ‘title’ ) is always stuck to it’s initial value…

What is the problem here ?

Best

Mark

>Solution :

Don’t try to override the view controller’s title property. Instead, create your own:

class vc1: UIViewController {
    @IBOutlet weak var lbl_title: UILabel!
    
    var myTitle = "initial value"
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        lbl_title.text = myTitle
    }
}

class ViewController: UIViewController {
    
    @IBOutlet weak var btn_go: UIButton!
    
    @IBAction func btn_gogogo(_ sender: Any) {
        
        let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "vc1") as! vc1
        
        vc.myTitle = "bla"
        
        self.present(vc, animated: true, completion: nil)
    }
    
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading