Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.button1.invalidateIntrinsicContentSize()
    self.button1.sizeToFit()

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

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)?

like image 625
vagrant Avatar asked Apr 20 '15 02:04

vagrant


1 Answers

You can use the contentEdgeInsets and titleEdgeInsets to implement that.

button2.setImage(image, for: .normal)
button2.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
button2.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 10)
button2.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, -10)
button2.setTitle("Button", for: .normal)
button2.sizeToFit()

button result

like image 83
Yuri Avatar answered Sep 20 '22 12:09

Yuri