3

What is a good way to have the image edge insets of a UIButton be left aligned while having the title completely centered? Such as the following:

enter image description here

The image would have a constant left inset, but the title would always be centered in the entire button. Most solutions that I have found date back 4 or 5 years, and they are based on manually calculating the necessary inset of the image while keeping a center alignment for the title.

Are there really no easy ways of doing this yet?

Daniel Larsson
  • 6,278
  • 5
  • 44
  • 82
  • Using constraints should do the job right? Set `Leading` to zero for the asset, and set the title center-aligned horizontally. – Stephenye May 09 '16 at 15:38
  • I assume that you mean to put the asset there as a subview to the button? Because I don't think using UIButton's built in image property lets you edit any constraints – Daniel Larsson May 09 '16 at 15:41
  • yea. alternatively do left alignment for control alignment for the button and a UILabel additionally for the title – Stephenye May 09 '16 at 15:50
  • Solution 1: Subclass UIButton and override `- (CGRect)titleRectForContentRect:(CGRect)contentRect` and `- (CGRect)imageRectForContentRect:(CGRect)contentRect` method. Solution2 : Modify `titleEdgeInsets` and `imageEdgeInsets` property of `UIButton`. – KudoCC May 10 '16 at 05:11

2 Answers2

0

You can set asset left aligned by using an image for your button and set horizontal alignment to left. For the title, you could add an additional UILabel and constraint it in a horizontal center-aligned manner.

button with asset left aligned set horizontal alignment

Stephenye
  • 806
  • 6
  • 12
  • Thank you for the input. I am aware that I can achieve this by using subviews, but I would rather not. It makes things like button states suddenly become a pain in the ****. – Daniel Larsson May 09 '16 at 16:08
  • The concern about button states is indeed a valid argument. Then you might want to try to use two buttons in a UIView container. One button is for the asset, one for the title. And constraint them according to your requirement. – Stephenye May 09 '16 at 16:12
0

you can set edge to change position of text and image of button

enter image description here

set Left Top Bottom and right according your requirement.