为具有图像的 UIButton 设置标题



我无法使用标准[button setTitle:@"Title"..]为我的UIButton设置标题我现在在UIButton上放一个UILabel,但我无法让标签在auto-layout中完美对齐。
注意:我有一张UIButton的图像

"设置"按钮 背景图像并将标题设置为按钮

[button setBackgroundImage:[UIImage imageNamed:@"yourButtonImageName"] forState:UIControlStateNormal];
[button setTitle:@"Title" forState:UIControlStateNormal];
[button.titleLabel setNumberOfLines:0];

将图像设置为按钮的背景。然后标题应该是可见的。

如果仍需要在按钮上放置标签,可以在代码中添加自动布局约束。他们在这种情况下工作。

编辑:在 Swift 中用于操场的示例:

import UIKit
import XCPlayground
let hostView = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 480))
hostView.layer.borderWidth = 1
hostView.layer.borderColor = UIColor.grayColor().CGColor
let button = UIButton.buttonWithType(.Custom) as! UIButton
button.backgroundColor = UIColor.redColor()
hostView.addSubview(button)
button.setTranslatesAutoresizingMaskIntoConstraints(false)
button.setTitle("This is a really long title for this button", forState: .Normal)
button.titleLabel!.numberOfLines = 0
NSLayoutConstraint.activateConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|-50-[button(100)]", options: nil, metrics: nil, views: ["button": button]))
NSLayoutConstraint.activateConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-50-[button(100)]", options: nil, metrics: nil, views: ["button": button]))
XCPShowView("Host View", hostView)
您可以使用带有

标题和图像的UIButton,但您必须注意图像和标题edgeInset例如[btn setTitleEdgeInsets:UIEdgeInsetsMake(70.0, -150.0, 5.0, 5.0)];

另请参阅此答案了解详细信息

在这种情况下,我建议创建自己的自定义视图。创建视图并将标签和 uiimageview 作为子视图

包含在内根视图:
++++++++++++
UIImageView

----------------------UILabel
++++++++++++

然后,您可以将点击手势添加到根视图以模拟按钮行为。

最新更新