swiftuiviewcontrolleruikitchildviewcontroller

Child View Controller and Margin


I have a child view controller as below.

import UIKit
class SampleChildViewController : UIViewController {

    let imageView : UIImageView = {
        let imageview = UIImageView()
        imageview.translatesAutoresizingMaskIntoConstraints = false
        imageview.clipsToBounds = true
        imageview.contentMode = .scaleAspectFit
        imageview.image = UIImage(named: "cat")
        return imageview
    }()


    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(imageView)

        NSLayoutConstraint.activate([
            imageView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 8),
            imageView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 8),
            imageView.widthAnchor.constraint(equalToConstant: 150),
            imageView.heightAnchor.constraint(equalToConstant: 150)
            ])
    }


}

then I have my parent view controller like below. I have added the child view controller into the parent view controller as shown below.

import UIKit

class ViewController: UIViewController {

    let child : SampleChildViewController = SampleChildViewController()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.white
        child.view.translatesAutoresizingMaskIntoConstraints = false
        addChild(child)
        view.addSubview(child.imageView)
        child.didMove(toParent: self)

    }


}

Now the problem is I have a strange margin problem in the parent view controller for the image view. As you can see in the screenshot below, the image view is hidden behind the navigation bar. If I make the child view controller as the root view controller and load the application, then the image view is positioned correctly. How to over come this issue?

enter image description here


Solution

  • You don't give the child view neither a frame nor constraints

    child.view.translatesAutoresizingMaskIntoConstraints = false 
    

    Also you should add view not imageView

    view.addSubview(child.view) 
    NSLayoutConstraint.activate([
       child.view.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 8),
       child.view.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: 8),
       child.view.leftAnchor.constraint(equalTo: view.leftAnchor),
       child.view.rightAnchor.constraint(equalTo: view.rightAnchor),
    ])
    

    and set

    navigationController?.navigationBar.prefersLargeTitles = false