changing constraints values depending on which iPhone the user use

Because all iPhones are using wC hR screen category I can't find a way to change some constraints between, say, iPhone 11 Pro max and iPhone 8 which has a very different screen size.

Is there a way to do so? or I just have to come up with a design fitting all iPhone screen sizes

1 answer

  • answered 2020-03-25 13:58 denis_lor

    I think checking each iPhone model is not really scalable and as well seems redundant.

    1) Something you can do in my opinion is start with a base iPhone Model you want to support, lets say iPhone SE, make your design fit well in iPhone SE and then at runtime, scale up to the current device screen size.

    You will get a scale ratio such as 1.2, 1.8..etc that you can apply (at runtime) to constraints such as font sizes maybe:

    var scaleRatio: CGFloat = {
        let iPhoneSEWidth: CGFloat = 320
        let currentDeviceWidth = UIScreen.main.bounds.size.width
        return currentDeviceWidth/iPhoneSEWidth

    And can apply that like:

    label.font = font.size(12 * scaleRatio)

    where 12 is the font size that fits well in iPhone SE (your base) and then at runtime it scales to the current ratio between your base screen size and the current iPhone screen size.

    2) Another thing you could do in UI Design, is probably instead of defining a specific constraint such as width or height or other anchor's constants is to define a view's anchor constraints as proportionally to other views' anchor constraints; for example you might want width of a view to always be half or approximately visually half of its container width, you can use multiplier:

    childView.widthAnchor.constraint(equalTo: containerView.widthAnchor, multiplier: 0.5).isActive = true

    It all depends on which strategy better fits what kind of constraints you want to scale up, and how you want to scale them up, but I think following those two mindset, can bring you to a good UI scaled in different iPhone Screens.