vagrant vagrant - 6 months ago 94
iOS Question

UIButton sizing wrong with image and title inset

It does not seem like UIButton instrinsicSize and/or sizeToFit takes a title left edge inset into account, or something is messed up with my expectations.

To demonstrate, I have two Custom type buttons in a view, both with the title "Button". I want to add an image to the button to the left of a title.

var image = UIImage(named: "circledPlay")
image = image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)

self.button1.setImage(image, forState: UIControlState.Normal)

self.button2.setImage(image, forState: UIControlState.Normal)
self.button2.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0)

The result is as follows:

screen shot

Note the second button is being truncated.

So my question would be if anybody has seen this before (and hopefully has a solution) or am I confused and this is behaving as expected (and hopefully knows the right way to do this)?

Answer Source

As it says in the documentation, for titleEdgeInsets: "The button does not use this property to determine intrinsicContentSize and sizeThatFits:". So, setting the titleEdgeInsets just moves the title label, but doesn't affect the size of the button. If you want the button to have more padding around the content, set the contentEdgeInsets as well. I don't think you need to call either sizeToFit, or invalidateIntrinsicContentSize (but 'm not sure about that).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download