Search code examples
iosswiftuiscrollviewautolayoutconstraints

How to use Auto Height and Scroll View at the same time in iOS?


So I am making a login screen and I am using auto height constraints to fit all the contents in my screen.

There is a problem with this approach, although it will work fine in Portrait mode, it will have problem in landscape mode, the fields will be too small in landscape mode.

How can I solve this problem, if I use scroll view then I will have use fix height for all of my contents, and I don't want that, as it will look ugly in smaller screens, is there are work around for this case, can scroll view only activate when the screen is rotated otherwise contents should use auto height constraint??

Portrait Mode Landscape Mode

So what I want is: My textfields to have 0.07% of my phone screen but every textfield should not subceed (be inferior) to height constraint 40.

If for some reason 0.07% of screen is less than 40 height constraint, then activate scroll view and keep height to a minimum of 40, if 0.07% is more than 40 height then keep that height.

No coding please (if else conditions), just use storyboard to achieve this.


Solution

  • You need two height constraints - The aspect ratio constraint that you already have, plus a second height constraint of >= 40.

    Set the priority of the aspect ratio constraint to a lower value than the new height constraint. E.g. Set the aspect ratio constraint to 750 and leave the new height constraint at the default of 1000.

    With this set of constraints the minimum height of the view will be 40 (set by the required constraint) but can be greater (if set by the aspect ratio constraint). The different priorities avoids a conflicting constraints warning.