Search code examples
uibuttonautolayoutswift4width

UIButton width doesn't increase based on text if insets are given


I have given trailing, top and height constraints to the button. As you can see in the attached screenshot, if I remove all the insets given, then button looks perfect and button fits based on text length.

But I want to give right-left title insets as well as left image inset.

Then button is not displaying text properly as shown in the attached screenshot.

enter image description here


Solution

  • Auto-layout can be a little tricky when adjusting the Title Label of a UIButton.

    From Apple's docs for titleEdgeInsets:

    This property is used only for positioning the title during layout. The button does not use this property to determine intrinsicContentSize and sizeThatFits(_:).

    You have a couple options...

    One is to subclass UIButton and override .intrinsicContentSize.

    Another option, which may be better for your case, is to adjust the Content Insets instead of the Title Insets.

    As you described, this button has Top / Trailing / Height constraints:

    enter image description here

    enter image description here

    Note that the Left value for the Image Inset is a negative value. You may / probably will want to tweak the values I used.

    enter image description here