Reputation: 1003
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];
Upvotes: 0
Views: 2644
Reputation: 149
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.
Upvotes: -1
Reputation: 1753
[button setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[button setContentVerticalAlignment:UIControlContentVerticalAlignmentTop];
//Use you values for edge insets here.
[button setTitleEdgeInsets:UIEdgeInsetsMake(20.0f, 10.0f, 0.0f, 0.0f)];
Upvotes: 0
Reputation: 8218
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)];
Upvotes: 4
Reputation:
You need to set the background image of the button instead:
[button setBackgroundImage:[UIImage imageNamed:@"foo"] forState:UIControlStateNormal];
Upvotes: 1