0

I have set an image in a UIButton but I need to set the title above this image. How can I do this?

[button setImage:[UIImage imageNamed:@"btn_select_s.png"] forState:0];
[button setImage:[UIImage imageNamed:@"btn_select_p.png"] forState:1];
[button setTitle:@"my title" forState:0];
Ladessa
  • 985
  • 4
  • 24
  • 50
  • possible duplicate of [iPhone SDK: UIButton with both image and text possible?](http://stackoverflow.com/questions/4344847/iphone-sdk-uibutton-with-both-image-and-text-possible) – rishi Feb 20 '13 at 16:47

4 Answers4

4

You can use UIButton's titleEdgeInsets and imageEdgeInsets to position title and image as you want.

See Apple's UIButton reference documentation

For example, in a UIButton subclass:

[self setImageEdgeInsets:UIEdgeInsetsMake(imageFrame.origin.y, imageFrame.origin.x, 0, 0)];
[self setTitleEdgeInsets:UIEdgeInsetsMake(labelFrame.origin.y, labelFrame.origin.x, 0, 0)];
Marcos Crispino
  • 8,018
  • 5
  • 41
  • 59
1

You need to set the background image of the button instead:

[button setBackgroundImage:[UIImage imageNamed:@"foo"] forState:UIControlStateNormal];
0
[button setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[button setContentVerticalAlignment:UIControlContentVerticalAlignmentTop];

//Use you values for edge insets here.
[button setTitleEdgeInsets:UIEdgeInsetsMake(20.0f, 10.0f, 0.0f, 0.0f)];
Shashank
  • 1,743
  • 1
  • 14
  • 20
-1

There is a convenient UIButton subclass here:
https://github.com/lionhylra/FlexButton

It has features like: - It provides 4 layout styles.
- It works as simple as UIButton.
- When you adjust the size of button, the size of imageView and titleLabel will change accordingly and correctly. They will not be put into disorder. This is the essential difference to using edge inset.
- TitleLabel and imageView will always be centered vertically and horizantally.

Yilei He
  • 149
  • 2
  • 7
  • Your answer only provides examples in Swift. The question is specifically tagged with Objective-C. Consider posting your example with an Objective-C based answer. – Acludia Mar 06 '17 at 21:26