Search code examples
iosxcodeautolayoutconstraintssize-classes

How to change the height of the view based on width


My views width will change according to the device width but I want to change the height according to that I don't want that to be static.

I couldn't find any constraint that can take care of this.

I heard aspect ratio can do this. But I tried It doesn't seem to work.

How it is generally achieved?


Solution

  • Use concept of aspect ratio with AutoLayout to update your view with respect to height & width. Use multiplier to update aspect ratio. Here are snap of aspect ration assignment and how to update it's multiplier

    enter image description here enter image description here

    Logic of Multiplier:
    1:1 = Height and width of your image will remain same
    2:1 = Your width or height is 2x with respect to each other and create a rectangle. Here Height will be 2x or width will be 2x, it depends upon first item and second item in constraint.

    Logic of Priority: Priority assigns, priority to specific constraint when it conflicts with another constraint of same view. e.g. if you have set a view with 1:1 aspect ratio, with 100 height & 100 width and centred in Main View. Now you also assign Left (margin)/Leading constraint as fix value like 200. In that case for different size of screen width, Centred alignment and/or Leading alignment and/or aspect ration will conflict each other. At this point you need to update priority between 0-1000, according to your requirement for adjustment of design.

    Share me your design, I will give your exact logic, how to use this concept