Search code examples
iosnslayoutconstraint

Why is ratio constraint not respected on iPhone XR/Xs Max?


I have a small UIImageView for displaying a user's profile photo. This looks fine on iPhone 6S, but when I run it on iPhone XR, the image is reduced to a tiny dot on the screen. I tried with simulators of different models, this problem only appears on XR/Xs Max simulators.

In the end, I found the problem: I had 2 constraints on this UIImageView: a width constraint of 32 points and a ratio constraint of 1. When I delete the ratio-constraint and add a height constraint of 32 points, all works fine.

I am wondering what causes iPhone XR/Xs Max to fail to respect the ratio-constraint? Is ratio constraint no longer supported in new models?

The simulators are all running iOS 12.2.

--EDIT--

Another UI layout issue only on XR/Xs Max, not related to ratio. I put a UIImageView into a container View, and set its frame like this:

imageView.frame = self.containerView.bounds
imageView.contentMode = .scaleAspectFit

The imageView look fine on all other models, filling the containerView. But on XR/XsMax, there is a margin on the right and bottom:

enter image description here

What am I missing here?


Solution

  • In the end, I found the problem: I had 2 constraints on this UIImageView: a width constraint of 32 points and a ratio constraint of 1.

    That does work. In all probability you configured the aspect ratio constraint incorrectly.

    imageView.frame = self.containerView.bounds
    

    Here, everything depends on when you say this. If you say it too early, such as in viewDidLoad, the containerView itself does not yet have its real bounds, so you'll end up with a wrong result. This is why using constraints is so much better. Using constraints, you can guarantee that the image view will fit its superview.

    So go back to using constraints, configure the aspect ratio correctly, and all will be well.