iosobjective-cswiftnslayoutconstraintvisual-format-language

How to prevent UIButton from exceeding its parent UIView's width with autolayout


Is that possible to create a MaxWidth constraint to prevent UIButton from exceeding its parent UIView's width?

UIButton is created programmatically and centered horizontally in its parent UIView using V:[ParentView]-(<=1)-[Button] constraint, but when the text is too large, button's width exceeds ParentView.

NOTE: I do not want to add leading/trailing constraints, which will force the button always be the same width as the parent. I really need the button to be center horizontally so when the text is short, it will not cover the whole width.


Solution

  • You can set your button's widthAnchor to be less than or equal to its parentView's widthAnchor:

    button.widthAnchor.constraint(lessThanOrEqualTo: parentView.widthAnchor, multiplier: 1).isActive = true