[英]Set title for UIButton that has an image
我无法使用标准的[button setTitle:@"Title"..]
来设置UIButton
标题,现在我将UILabel
放在UIButton
顶部,但是我无法使标签在auto-layout
完美对齐。
注意:我有一个图像的UIButton
设置按钮背景图片并将标题设置为按钮
[button setBackgroundImage:[UIImage imageNamed:@"yourButtonImageName"] forState:UIControlStateNormal];
[button setTitle:@"Title" forState:UIControlStateNormal];
[button.titleLabel setNumberOfLines:0];
您可以将UIButton与Title和Image一起使用,但必须注意图像和标题edgeInset
,例如[btn setTitleEdgeInsets:UIEdgeInsetsMake(70.0, -150.0, 5.0, 5.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)
在这种情况下,我建议您创建自己的自定义视图。 创建一个视图,并包含标签和uiimageview作为子视图
根视图:
++++++++++++
UIImageView
----------------------
UILabel
++++++++++++
然后,您可以将tapgesture添加到rootview来模拟按钮行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.