UILabel Swift/Storyboard returns nil

731 views Asked by At

I created a navigation controller with a view controller inside, containing a label. This label should be changed, when the view controller is loaded on tapping a button.

class ViewController: UIViewController {
    @IBOutlet weak var btnEmergency: UIButton!


    override func viewWillAppear(animated: Bool) {
        self.btnEmergency.backgroundColor = UIColor.redColor();
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func btnEmergencyTapped(sender: AnyObject) {
        let emergencyViewController = storyboard?.instantiateViewControllerWithIdentifier("EmergencyViewController") as! EmergencyViewController
        emergencyViewController.emergencyLabel?.text = "Notruf"
        navigationController?.pushViewController(emergencyViewController, animated: true)
    }
}

But the label text does not change when loaded. I am relatively new to SWIFT so I try to learn my ropes at the moment using optionals. So I guess the reason is, that the label is not yet instantiated when the view is being loaded on pressing the button. Therefore the default text is being shown and not the text I want to have appear on screen.

I am a little bit stuck at the moment, how to correctly change the label text, when this is an optional. So I guess I cannot expect the label to be there, when I call it. But how do I handle this correctly?

1

There are 1 answers

0
Shamas S On BEST ANSWER

Instead of this, the correct way is to set a property of your emergencyViewController.

In your emergencyViewController viewDidLoad set your label text according to the property set previously.

Anything that you do between initialize of a viewController to viewDidLoad will not take effect.