Tulleb
Tulleb

Reputation: 9196

Separate image's position from title's length on UIButton

UIButton image position is dependent of the current title length for the same image.

The first UIButton image is centered if there is no title set. And the second one is shifted to the left when there is one ("like").

Thumb image is centered if there is no title set Thumb image is shifted to the right when a title is set

How can I always keep my UIButton image at the center of my button? Even if the title appears on the top of it?

I already tried with imageInset and it's the same problem. I'd also like not to use a different UIImageView other than the default UIButton's one.

Upvotes: 2

Views: 1588

Answers (1)

Vidhyanand
Vidhyanand

Reputation: 5369

You can use below code...

// the space between the image and text
CGFloat spacing = 6.0;

// lower the text and push it left so it appears centered 
//  below the image
CGSize imageSize = button.imageView.frame.size;
button.titleEdgeInsets = UIEdgeInsetsMake(
  0.0, - imageSize.width, - (imageSize.height + spacing), 0.0);

// raise the image and push it right so it appears centered
//  above the text
CGSize titleSize = button.titleLabel.frame.size;
button.imageEdgeInsets = UIEdgeInsetsMake(
  - (titleSize.height + spacing), 0.0, 0.0, - titleSize.width);

Source: UIButton: how to center an image and a text using imageEdgeInsets and titleEdgeInsets?

You can try for alternate solutions using below link

UIButton Image + Text IOS

Hope it helps you...

Upvotes: 1

Related Questions