2015-04-22 35 views
0

UIButton使用标准[button setTitle:@"Title"..] 我现在放置UILabelUIButton的顶部,我不能设置标题,但我不能让标签在auto-layout完美对齐。
注:我对UIButton为的UIButton设置标题具有图像

+0

通过从下拉选项卡上的右侧 –

回答

0

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

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

编辑:斯威夫特例在操场使用:

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) 
+0

此works..but我需要在此更新软件包中选择图像。 。我的意思是,我可以增加标题行数,就像我可以在UILabel中设置的那样,使内容不会超出按钮的边界? –

+1

将该按钮的textLabel的'numberOfLines'属性设置为0并使该按钮足够大。 – dasdom

+0

无法让它工作..什么是确切的语法? –

0

您可以使用使用与标题和图片一个UIButton的图像,但你必须要照顾形象和标题edgeInset例如[btn setTitleEdgeInsets:UIEdgeInsetsMake(70.0, -150.0, 5.0, 5.0)];

也看到这个answer为细节

-1

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

RootView:
++++++++++++
的UIImageView
------------- ---------
的UILabel
++++++++++++

那么你可以添加tapgesture到rootview模拟按钮的行为。

+0

在这种情况下重新创建'UIButton'似乎是一种矫枉过正的行为。 – dasdom

1

设置按钮背景图像,并设置标题按钮

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