I have a button inside a view. I have set image for my button in interface builder. The constraints that I have added to my button in interface builder is:
Right space to superview = 10
top space to superview = 10
bottom space to superview >= 10
left space to a label >= 10
All thing work fine and I have no problem with my layout. But when I log the button constraints with this code:
NSLog(@"constraints for btnBack is: %@", self.btnBack.constraints);
the console logs:
constraints for btnBack is:(
"<NSContentSizeLayoutConstraint:0x7c35c400 H:[UIButton:0x7c3588a0(102)] Hug:250 CompressionResistance:750>"
"<NSContentSizeLayoutConstraint:0x7c35c450 V:[UIButton:0x7c3588a0(92)] Hug:250 CompressionResistance:750>")
I know that the top and left and right and bottom constraints shouldn't log here because they are the superview constraints not the button constrains. But here I didn't add any width and height constrains to my button(even in code).
Why constraints height and width are logged in the console?
Open the Align menu with the yellow button selected and check Horizontally in Container, then click Add 1 Constraint. Now, select both buttons at the same time using the Shift key and, in the Align menu, check Leading Edges. Again, actually install the constraint by clicking Add 1 Constraint.
Auto Layout constraints allow us to create views that dynamically adjust to different size classes and positions. The constraints will make sure that your views adjust to any size changes without having to manually update frames or positions.
If a view has a natural width based on its content, it returns that width as intrinsicContentSize.width
. Otherwise, it sets intrinsicContentSize.width
to UIViewNoIntrinsicMetric
.
Similarly, if it has a natural height, it returns that width as intrinsicContentSize.height
. Otherwise, it sets intrinsicContentSize.height
to UIViewNoIntrinsicMetric
.
A button has a natural size (both width and height), determined by its title, font, image, and maybe other details. So its intrinsicContentSize.width
and intrinsicContentSize.height
are both valid sizes, not UIViewNoIntrinsicMetric
.
When intrinsicContentSize.width != UIViewNoIntrinsicMetric
, auto layout installs a special constraint of type NSContentSizeLayoutConstraint
on the view. Similarly, when intrinsicContentSize.height != UIViewNoIntrinsicMetric
, auto layout installs an NSContentSizeLayoutConstraint
on the view.
For the details of what these special constraints do, see this answer.
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