Search code examples
iosswiftuitableviewuiimageviewios-autolayout

How to set up different Auto Layout constraints for different screen sizes


I have a tableView with static cells. The cell contains an ImageView which fills it completely. And I have another smaller ImageViews atop. I position this ImageViews with constraints. I have a question about resizing the constraints. How can I set different constraint constants for different devices sizes without programming if/else loops. Is there a way to set it in the storyboard? I have a leading constraint to parent layout for example with an constant value of 10. This is okay for the iPhone 5 screen, but on an iPhone 6/ 6 plus screen it should be higher than 10.

iPhone5 Autolayout

Screen Shot

iPhone6 Autolayout

Screen shot


Solution

  • Without writing a single line of Code!

    Once my junior developer asked me the same question that how can I differentiate between iPhoneSE and iPhone6 for some constraint at that time there was only one solution that was writing some thing like

    if device == iPhoneSE { 
       constant = 44 
    } else if device == iPhone6 {
       constant = 52
    }
    

    To overcome this issue I created a library Layout Helper so now you can update constraint for each device without writing a single line of code.

    enter image description here

    Step 1

    Assign the NSLayoutHelper to your constraint

    enter image description here

    Step 2

    Update the constraint for the device you want

    enter image description here

    Step 3

    Run the app and see the MAGIC

    enter image description here