Liam
Liam

Reputation: 192

The space between title and text on UIButton is not correct when adjusting titleEdgeInsets and imageEdgeInsets

I want to adjust the space between text and image on UIButton,

let space = 10
button.contentHorizontalAlignment = .left
button.titleEdgeInsets = UIEdgeInsets(top: 0, left: space, bottom: 0, right: 0)

enter image description here

It looks well, the space in the picture is absolutely 10.

And now, I want them center,

let space = 10
button.contentHorizontalAlignment = .center
button.titleEdgeInsets = UIEdgeInsets(top: 0, left: space, bottom: 0, right: 0)

enter image description here

It looks much smaller, and the space is only 5. I find it from Reveal.

Why the space is reduced by half?

I searched, and this tells me how to make title and image center as a single entity. And it adjust their space like this:

CGFloat spacing = 10; // the amount of spacing to appear between image and title
tabBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, spacing);
tabBtn.titleEdgeInsets = UIEdgeInsetsMake(0, spacing, 0, 0);

Yes, it truly works well, but why? From the letter, the space should be 20, doesn't it?

Here is an example, any helps?

Thanks in advance.

Upvotes: 2

Views: 3134

Answers (1)

Ekramul Hoque
Ekramul Hoque

Reputation: 692

You Didn't set imageEdgeInsets like this :

rightButton.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 10)

So total Code is here :

leftButton.contentHorizontalAlignment = .left
        leftButton.imageView?.backgroundColor = .red
        leftButton.titleLabel?.backgroundColor = .gray
        leftButton.titleEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0)

        rightButton.contentHorizontalAlignment = .center
        rightButton.imageView?.backgroundColor = .red
        rightButton.titleLabel?.backgroundColor = .gray
        rightButton.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 10)
        rightButton.titleEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0)

Reason: Actually you need to set imageEdgeInsets both time left alignment or center alignment But when its left alignment image there is no space to set Insets at the right side.

Seet this code :

leftButton.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 100)

Here is also no space .

So home you get some idea how insets work :

For your more Help :

Click here

Upvotes: 3

Related Questions