Search code examples
iosxcode-storyboarduistackviewsize-classes

UIStackView subviews with size classes


Trying to achieve UIStackView with 2 labels for iPhone and 3 labels for iPad using size classes.

View hierarchy

  1. Default size class

    [UIStackView] 
      [UILabel 1] [UILabel2]
    [UIStackView] 
    

    enter image description here

  2. RxR size class

    [UIStackView] 
      [UILabel 1] [UILabel2] [UILabel3]
    [UIStackView] 
    

    enter image description here

It looks exactly as expected in Storyboard as you can see in the above screenshots but on simulator iPad view is messed up.

iPhone Output (okay)

enter image description here

iPad Portrait Output (messed up)

enter image description here

iPad Landscape Output (messed up) enter image description here

What's happening in iPad?? Is it a bug or I'm missing something? Thanks.

I have created a sample project.


Solution

  • Follow below steps to achieve your requirements :

    • Drag one horizontal Stackview in to your interface builder
    • set it's constraints like : top,leading, =trailing and fixed height
    • Drag and drop three labels in to it and select all together and set one constraint : Equal width
    • now select second or middle label and from attribute inspector click on + button beside installed and select Regular for both width and height. It will add regular,regular variation and uncheck the checkbox for that R,R variation. Refer below screen shot for better understanding,

    enter image description here

    And you are done! now you your center label will not show in iPad and every label will be displayed in iPhone!

    See below result screenshot of iphone and ipad in my case!

    iPhone :

    enter image description here

    iPad :

    enter image description here

    Update :

    If you want two to hide label in iPhone and show in iPad then add one more variation : Compact Width Regular Height for middle label and uncheck the checkbox to uninstall. Refer below screenshot,

    enter image description here