0

So I want to instantiate a view controller from storyboard and change its 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.

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 its initial value.

What is the problem here?

Best

Mark

6
  • Why are you choosing to have title be static? Commented Jan 9, 2023 at 16:05
  • to be able to access it from the root vc !? Commented Jan 9, 2023 at 16:05
  • In the code you've shared, there's no reason for it to be static Commented Jan 9, 2023 at 16:07
  • you are right... understood :-) but my problem still remains unchanged Commented Jan 9, 2023 at 16:09
  • Have you tried wrapping the line where you set the title inside of a “DispatchQueue.main.async”? Commented Jan 9, 2023 at 16:12

1 Answer 1

1

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)
    }
    
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.