Search code examples
iosswiftchildviewcontroller

Peculiar top margin in the ImageView added from ChildViewController


I have created a child view controller as below. It has a UIImageView. I added the UIImageView to the view as below.

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.topAnchor),
            imageView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 10),
            imageView.widthAnchor.constraint(equalToConstant: 150),
            imageView.heightAnchor.constraint(equalToConstant: 150)
            ])
    }


}

This is how the parent view controller looks like.

class ViewController: UIViewController {

    let child : SampleChildViewController = SampleChildViewController()


    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.red

        child.view.translatesAutoresizingMaskIntoConstraints = false
        addChild(child)
        child.didMove(toParent: self)
        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),
            ])



    }


}

Now the problem is I have a strange top margin to the imageview as shown below. How to fix it?

enter image description here


Solution

  • problem is with imageview.contentMode = .scaleAspectFit. The boundary you see for the image is not the real boundary. Set the content mode as imageview.contentMode = .scaleAspectFill as it'll fill the whole view.

    It should look something below

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