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?
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

Child/SubView View Constraint

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

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]];
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With