Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 552
Shiva Avatar asked Dec 19 '25 00:12

Shiva


2 Answers

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

like image 60
Krunal Avatar answered Dec 20 '25 15:12

Krunal


Try with following easy way..

1) Give Leading and Trailing Constraint like below image.

enter image description here

2) Now set Top or Bottom or Other Constraint as per your design. For me i have settled Vertically Center.

enter image description here

3) Now set Height of UIView as per your Ratio which you want in design and after selecting that view just Drag and Drop on same view and select Aspect Ratio. XCode will automatically get Ratio Constraint. For ref. see below image.

enter image description here

like image 34
Abhishek Sharma Avatar answered Dec 20 '25 14:12

Abhishek Sharma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!