Search code examples
swiftxcodeautolayoutconstraints

AutoLayout with Multiple Images in XCode


I'm trying to use autolayout in XCode to position these two images like they are in the screenshot, but when I run the simulator, they're in the wrong position. Here is basically what I want to do:

  • scale the images up if the screen size goes up (and vice-versa)
  • have the dog picture just above the middle of the screen
  • have the loading picture a certain distance below the dog (i.e: loading.y = dog.y + screenheight/4)

I have not gotten the hang of autolayout yet so any direction to what constraints I should use would be appreciated.

Image of View Controller


Solution

  • You would really benefit from just spending time reading through auto-layout tutorials / articles / discussions / documentation / etc.

    Here is an example of what you are describing.

    Using these two images:

    enter image description here

    enter image description here

    You can lay out your image views in Storyboard like this:

    enter image description here

    The dog imageView has:

    • Centered horizontally
    • Bottom constrained 90% to the CenterY position (just above the middle)
    • Width is 50% of the safe-area width
    • Height determined by Aspect Ratio of 236:175 (the original size of the image)

    The loading imageView has:

    • Centered horizontally
    • CenterY constrained 1.75% to the CenterY position (effectively screenHeight / 4)
    • Width is 75% of the safe-area width
    • Height determined by Aspect Ratio of 368:76 (the original size of the image)

    and here is how it looks on 3 different device sizes:

    enter image description here

    The best way to learn this is to just work on it.