为具有图像的 UIButton 设置标题

Set title for UIButton that has an image

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

的图像

您可以使用带有标题和图像的 UIButton,但您必须处理图像和标题 edgeInset 例如 [btn setTitleEdgeInsets:UIEdgeInsetsMake(70.0, -150.0, 5.0, 5.0)];

另见此answer了解详情

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

如果您仍然需要在Button 上放置Label,可以在代码中添加Auto Layout 约束。他们在这种情况下工作。

编辑: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)

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

根视图:
++++++++++++
UIImageView
----------------------
UILabel
++++++++++++

然后你可以在rootview中添加taggesture来模拟按钮的行为。

设置按钮背景图片并设置按钮标题

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