Search code examples
iosswiftsetuielement

Swift - Set a UI element from outside


I have this UIViewController

import UIKit

class UIViewController1: UIViewController {

    @IBOutlet weak var someTitle: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

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

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

And I am trying to set someTitle when I instantiate it from another view controller:

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.   
    }

    override func viewDidAppear(animated: Bool) {
        let stb = UIStoryboard(name: "Main", bundle: nil)

        let vc1 = stb.instantiateViewControllerWithIdentifier("someSTBID") as! UIViewController1
        vc1.someTitle.text = "My Title" // it fails here!!!!!
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }    
}

The reason it fails at the line above is that I was trying to force unwrapping a nil optional, which is someTitle.

Please show me a way to set someTitle in this situation.


Solution

  • Your second UIViewController hasn't been loaded yet, so the someTitle IBOutlet will be nil. You got two options:

    1. The easy one: you force the load of the second UIViewController, for example: vc1.view is enough and then you set it (I don't recommend this)
    2. The proper one: you let the second UIViewController be responsible for setting its own title at the right time. If you need to pass the "My title", you can simply pass it via a function like configureVc(title: String), or by exposing a variable like var title: String, so on viewDidLoad of the second UIViewController you would someTitle.text = title.