我已经在UIButton
中设置图像,但我需要设置此图像上方的标题。我怎样才能做到这一点?标题在UIButton与图像
[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];
我已经在UIButton
中设置图像,但我需要设置此图像上方的标题。我怎样才能做到这一点?标题在UIButton与图像
[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];
您需要设置按钮的背景图像,而不是:
[button setBackgroundImage:[UIImage imageNamed:@"foo"] forState:UIControlStateNormal];
Thx很多!它的工作 – Ladessa 2013-02-20 16:52:25
可以使用的UIButton的titleEdgeInsets和imageEdgeInsets如要放置标题和图像。
See Apple's UIButton reference documentation
例如,在一个UIButton子类:
[self setImageEdgeInsets:UIEdgeInsetsMake(imageFrame.origin.y, imageFrame.origin.x, 0, 0)];
[self setTitleEdgeInsets:UIEdgeInsetsMake(labelFrame.origin.y, labelFrame.origin.x, 0, 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)];
有方便的UIButton子类在这里:
https://github.com/lionhylra/FlexButton
它具有的功能,如: - 它提供4种布局样式。
- 它的工作原理与UIButton一样简单。
- 当您调整按钮的大小时,imageView和titleLabel的大小将相应地正确更改。他们不会陷入混乱。这是使用边缘插入的本质区别。
- TitleLabel和imageView将始终以垂直和水平居中。
你的答案只提供了Swift中的例子。这个问题专门用Objective-C标记。考虑发布一个基于Objective-C的答案。 – Acludia 2017-03-06 21:26:29
[iPhone SDK:UIButton同时具有图像和文字可能吗?]的可能重复?(http://stackoverflow.com/questions/4344847/iphone-sdk-uibutton-with-both-image-and-text-possible) – rishi 2013-02-20 16:47:16