Search code examples
iosswiftautolayoutuikit

UIKit: Constraints with respecting NavBar and ignoring safe area at the bottom


I'm following by one of the video of Paul Hudson and trying to recreate detail screen with full screen image. By following the video I set up constraints to Reset to suggested contains but I have different values compering to video. I tried to play around with settings but can't get the expected result...

Constraints:

Image View.top = topMargin - 44
Image View.centerX = centerX
Image View.centerY = centerY
Image View.leading = Safe Area.leading

Result:

enter image description here

Expected:

enter image description here

Question: How to set up constraints to respect NavigationBar and took all other place in the screen, like in expected image?


Solution

  • Assuming your VC is embedded in a navigation controller, you basically want to constraint the left, right and bottom of the image view to be equal to its superview, and the top of the image view to the top layout guide:

    enter image description here

    You should select the image view, and add the constraints using this pop up:

    enter image description here

    Click on all four of the thingys I circled. If the first or second items of the constraints added are incorrect, change them by selecting the constraint and using the drop down here:

    enter image description here

    Alternatively, just add them with code:

    imageView.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([
        imageView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
        imageView.leftAnchor.constraint(equalTo: view.leftAnchor),
        imageView.rightAnchor.constraint(equalTo: view.rightAnchor),
        imageView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
    ])