1

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.

Vertexwahn
  • 7,709
  • 6
  • 64
  • 90
quanguyen
  • 1,443
  • 3
  • 17
  • 29

2 Answers2

3

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.
Rui Peres
  • 25,741
  • 9
  • 87
  • 137
0

Do you need it to go into the superclass viewDidAppear, because it should work if you put it into the superclass viewDidLoad(). I hope that helps you and future viewers.

EQOxx123
  • 244
  • 1
  • 2
  • 9