简体   繁体   English

UIButton中带有图像的标题

[英]Title in UIButton with Image

I have set an image in a UIButton but I need to set the title above this image. 我已经在UIButton设置了图像,但是我需要在该图像上方设置标题。 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];

You can use UIButton's titleEdgeInsets and imageEdgeInsets to position title and image as you want. 您可以使用UIButton的titleEdgeInsets和imageEdgeInsets来根据需要放置标题和图像。

See Apple's UIButton reference documentation 请参阅Apple的UIButton参考文档

For example, in a UIButton subclass: 例如,在UIButton子类中:

[self setImageEdgeInsets:UIEdgeInsetsMake(imageFrame.origin.y, imageFrame.origin.x, 0, 0)];
[self setTitleEdgeInsets:UIEdgeInsetsMake(labelFrame.origin.y, labelFrame.origin.x, 0, 0)];

您需要改为设置按钮的背景图像:

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

//Use you values for edge insets here.
[button setTitleEdgeInsets:UIEdgeInsetsMake(20.0f, 10.0f, 0.0f, 0.0f)];

There is a convenient UIButton subclass here: 这里有一个方便的UIButton子类:
https://github.com/lionhylra/FlexButton https://github.com/lionhylra/FlexButton

It has features like: - It provides 4 layout styles. 它具有以下功能:-提供4种布局样式。
- It works as simple as UIButton. -它像UIButton一样简单。
- When you adjust the size of button, the size of imageView and titleLabel will change accordingly and correctly. -调整按钮的大小时,imageView和titleLabel的大小将相应正确地更改。 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. -TitleLabel和imageView将始终垂直和水平居中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM