Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set width of custom subview to be 1/3rd of parent UIView which does not have width constraint?

I have a custom parent UIView (Say PView) which is defined by Left,Right,Top and Bottom constraints. Now I want to add a custom subview (say SView) to the PView with width equal to MIN of 200 and 1/3rd of PView.

I have the updateConstraints method in my PView class where I update the location constraints for SView. However, I am not sure how can I set its size, because I don't have the widthConstraint of PView?

like image 582
Akshay Shah Avatar asked Jan 23 '26 20:01

Akshay Shah


2 Answers

You can easily achieve this by proportional width feature in storyboard with Autolayout.

Give you PView a proportional width to a ratio of 1:3 to your superView(SView). Parent View Constraint Orange Super View(SView)

Child/SubView View Constraint Red Sub View

How to Give Proportional Constraint? You set ParentView and ChildView with equal width then double click on width constraint and set a ratio of 1:3. Width will always be 1/3 of parent view

Proportional Width Constraint

Coding Approach

[self.yourview addConstraint:[NSLayoutConstraint
                              constraintWithItem:self.yourview
                              attribute:NSLayoutAttributeHeight
                              relatedBy:NSLayoutRelationEqual
                              toItem:self.yourview
                              attribute:NSLayoutAttributeWidth
                              multiplier:(self.yourview.frame.size.height / self.yourview.frame.size.width)
                              constant:0]];
like image 73
Priyansh Avatar answered Jan 25 '26 12:01

Priyansh


Your parent view's constraint should be like : top,leading,trailing,bottom

Your subview's constraints should be like : top,leading,fixed height

Now select both view and set equal width constraint and then select that constraint and from attribute inspector change it's multiplier to 0.333.

That's it!

like image 44
Ketan Parmar Avatar answered Jan 25 '26 12:01

Ketan Parmar



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!