Micah Montoya
Micah Montoya

Reputation: 767

UIViewController call function in container view viewcontroller

Using Swift 3. This question has been around and there are quite a few examples. Unfortunately none of them have worked for me. I have a uiviewcontroller that has a container view. This container view has a segue to another view controller. Everything loads up correctly and displays correctly the first time. The problem that I am facing is that I have a button on the main uiviewcontroller which by tapping it, it will refresh the container view. This is where the problem is. The outlets in the child controller are nil.

This is how I am trying to all the function in the child controller.

let wcvc = self.storyboard!.instantiateViewController(withIdentifier: "WeatherCurrentViewController") as! WeatherCurrentViewController
    wcvc.callJson()

In the child controller the label is like this

 @IBOutlet var currentweather: UILabel!

But in the function that is called I get an error of unexpectedly found nil while unwrapping an Optional value when I try to do

 print(currentweather)

Anyone have an idea of what I can do to call a function in a view controller that is loaded by segue in a container view and still have the outlets be valid? Please let me know if more info is needed.

Found the solution. I needed to use segues identifiers and not the storyboard. Doing this

 private var currentEmbeddedViewController: WeatherCurrentViewController!     
 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let cvc = segue.destination as? WeatherCurrentViewController, segue.identifier == "CurrentWeather" {
        self.currentEmbeddedViewController = cvc
    }
} 

And calling the function in the controller like so

self.currentEmbeddedViewController.callJson()

Was the solution. This question offered the solution. Sorry to waste everyones time. Hopefully, this will help someone else.

Upvotes: 0

Views: 1178

Answers (1)

Noobass
Noobass

Reputation: 2014

The reason why you get an exception is that your currentweather label will get loaded from the storyboard only when the view of that view controller loads. This means, that when you try to call callJson() the view is not yet loaded and thus no IBOutlets are loaded yet as well, meaning they are nil.

I would suggest passing some data to theWeatherCurrentViewController and only on viewDidLoad updating the views. viewDidLoad guarantees that view and all the outlets are loaded and are not nil

Upvotes: 1

Related Questions