Edoardo
Edoardo

Reputation: 675

How to use container view programmatically

I created a ViewController, and I want to add in my ViewController a container view, here I set the container view inside my ViewController:

var containerView: UIView = {
    let view = UIView()
    view.translatesAutoresizingMaskIntoConstraints = false
    view.backgroundColor = .red
    return view
}()

func setUpViews() {
    view.addSubview(containerView)
    containerView.heightAnchor.constraint(equalToConstant: 300).isActive = true
    containerView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
    containerView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
    containerView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
}

Here I set my instance of SecondViewController in the containerView:

override func viewDidLoad() {
    super.viewDidLoad()

    setUpViews()

    let secondViewController = SecondViewController()

    secondViewController.willMove(toParent: self)

    containerView.addSubview(secondViewController.view)
    self.addChild(secondViewController)
    secondViewController.didMove(toParent: self)

}

In my SecondViewController, I declared label and a view, I set the label in the center of the view:

let label: UILabel = {
    let label = UILabel()
    label.text = "Hello!"
    label.translatesAutoresizingMaskIntoConstraints = false
    return label
}()

override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(myView)
        myView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        myView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        myView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
        myView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true

        view.addSubview(label)
        label.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        label.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true

    }

That's what I see in my app, but I aspected to see a label in the center of the gray view. It doesn't work like I aspected and I don't understand why.

image

Upvotes: 0

Views: 792

Answers (1)

DonMag
DonMag

Reputation: 77423

You need to set the frame and/or constraints on the loaded view:

override func viewDidLoad() {
    super.viewDidLoad()

    setUpViews()

    let secondViewController = SecondViewController()

    secondViewController.willMove(toParent: self)

    containerView.addSubview(secondViewController.view)

    // set the frame
    secondViewController.view.frame = containerView.bounds

    // enable auto-sizing (for example, if the device is rotated)
    secondViewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]

    self.addChild(secondViewController)
    secondViewController.didMove(toParent: self)

}

Upvotes: 2

Related Questions