Search code examples
iosxcodeautolayoutxcode8

Keeping aspect ratio and autolayout for different devices


I have labels and toolbars on the top and bottom of the screen with height constraints. And I got UIImage between toolbars. So toolbars and labels are keeping same height for different devices while space between toolbars is changeable.

My goal is to keep aspect ratio 1:1 for devices from SE to IPad and to center UIImage between toolbars by stretching it until it reach superview margins on sides or toolbars on top and bottom. I was tried different approaches but the best thing I could get is on below screenshot.

enter image description here

It's keeping aspect ratio but I can't figure out how to keep it centered between toolbars.

Constraints for UIImage:

enter image description here

Since I'm working on iOS 8 supported app I didn't use UIStackView and try to find a solution with constraints only.


Solution

  • You need to do following things :

    1. Add a new view (says, centerView) in between the yellow and green view and give it clear color and give below constraints

      • Leading, trailing to superview as constant = 0.
      • Top to yellow view as constant = 0
      • Bottom to yellow view as constant = 0
    2. Now in centerView add ImageView which have Apple logo and give below constraints.

      • Give it fixed height as you want.
      • give it vertically and horizontally centered w.r.t. its superView.