Hani
Hani

Reputation: 105

Child ViewController's view is nil when trying to add it to a View Container

I have two view controllers. The parent view controller has a view container that I'm trying to display the child view controller inside it. Here is my code:

Parent View Controller:

class ParentViewController: UIViewController {
    @IBOutlet weak var viewContainer: UIView! //View Container inside Parent View Controller


    override func viewDidLoad() {
        super.viewDidLoad()

        let sb = UIStoryboard(name: "Main", bundle: nil)
        let childVc = sb.instantiateViewController(withIdentifier: "ChildViewControllerStoryId") as! ChildViewController

        addChild(childVc)
        childVc.view.translatesAutoresizingMaskIntoConstraints = false
        viewContainer.addSubview(childVc.view)
        childVc.didMove(toParent: self)

    }
}

Child View Controller:

class ChildViewController: UIViewController {
@IBOutlet weak var textLabel: UILabel!
    override func viewDidLoad(){
        super.viewDidLoad()
        textLabel.text = "random text"
    }
}

I'm getting this error at "viewContainer.addSubview(childVc.view)" :

Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value: file /../../.swift

I think it's telling me that the view of the child view controller is nil. What seems to be the problem here?

Thanks!

Upvotes: 0

Views: 854

Answers (1)

nicog
nicog

Reputation: 112

This can happen if your ChildViewController does not properly have its class set in Interface Builder. Make sure it is, and comment back if that does not fix it.

Upvotes: 1

Related Questions