I wonder is there a way to programmatically retrieve the height constraint of a specific UIView
and change its value in the code? I have a situation where I have several UIViews
with four edges pinned in the IB and height constraints added (IB complains if I did not), but in the middle of the program I would need to change the height of the UIViews
and cause some UIViews
to be pushed downward in the view.
I know I can ctrl+drag the height constraints of each UIViews
and change their values in the code, but doing so would require me to wire dozens of them. So I think this is not efficient and not scalable in some way.
So I wonder is there a way to totally retrieve the height constraints of a specific view through code and change it dynamically?
Thanks!
Select the height constraint from the Interface builder and take an outlet of it. So, when you want to change the height of the view you can use the below code. Method updateConstraints() is an instance method of UIView . It is helpful when you are setting the constraints programmatically.
Clicking the Edit button in any of the constraints brings up a popover where you can change the constraint's relationship, constant, priority, or multiplier. To make additional changes, double-click the constraint to select it and open it in the Attribute inspector.
Add the button in the view, give it constraints and as you are using constraints, you can skip the button. frame and add widthAnchor and heightAnchor . At last activate them and keep translatesAutoresizingMaskIntoConstraints as false . Also, it will be better if you can add proper names.
First add height constraint to your .h
file:
//Add Outlet IBOutlet NSLayoutConstraint *ViewHeightConstraint;
Next, add the below code to your .m
file:
//Set Value From Here ViewHeightConstraint.constant = 100;
You can connect that specific constraint to your code from the interface builder like
And NSLayoutConstraint
has a constant property to be set which is your constant pin value.
If you're adding your constraints programmatically, you can surely benefit from the identifier property in NSLayoutConstraint
class. Set them and iterate over them to get that specific identifired constraint.
As the documentation says
extension NSLayoutConstraint { /* For ease in debugging, name a constraint by setting its identifier, which will be printed in the constraint's description. Identifiers starting with UI and NS are reserved by the system. */ @availability(iOS, introduced=7.0) var identifier: String? }
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