D. Cohen D. Cohen - 1 month ago 11
Swift Question

titleEdgeInsets for UIButton make no sense

I have an image and a title for a UIButton. I'm trying to get my image (15px in width) to be aligned left and my title to be aligned 5px left of that:

Button Example

The button is 215 in width, but I had to set my titleEdgeInset right to -44. This doesn't make sense. What are the maths to get -44?


It's because the image and title of a button are centered together by default.

For example, here's a 300px wide button with an image and text, no insets:

Default button spacing

Looks like I need the button contents shifted left by 60 pts, so -60 left inset and 60 right inset.

button.imageEdgeInsets = UIEdgeInsetsMake(0.0, -60.0, 0.0, 60.0)
button.titleEdgeInsets = UIEdgeInsetsMake(0.0, -60.0, 0.0, 60.0)

enter image description here


These insets would also work for the above example.

button.imageEdgeInsets = UIEdgeInsetsMake(0.0, -120.0, 0.0, 0.0)
button.titleEdgeInsets = UIEdgeInsetsMake(0.0, -120.0, 0.0, 0.0)

The button is centering its contents, so if you say "there are 2 more pts on the left" the button will move its contents over by 1 pt to keep them centered.

The rule is