I cannot set title for my UIButton
using the standard [button setTitle:@"Title"..]
I am right now placing a UILabel
on top of the UIButton
, but I cant get the label to be aligned perfectly in auto-layout
.
NOTE: I have an image for the UIButton

- 2,509
- 22
- 38

- 927
- 1
- 6
- 25
-
By selecting the image in the bundle from the drop down tab on the right side – Sidharth J Dev Apr 22 '15 at 09:41
4 Answers
Set button Background image and set title to button
[button setBackgroundImage:[UIImage imageNamed:@"yourButtonImageName"] forState:UIControlStateNormal];
[button setTitle:@"Title" forState:UIControlStateNormal];
[button.titleLabel setNumberOfLines:0];

- 206
- 3
- 10
You can use use a UIButton with Title and Image but you have to take care of image and title edgeInset
for example [btn setTitleEdgeInsets:UIEdgeInsetsMake(70.0, -150.0, 5.0, 5.0)];
also see this answer for details

- 1
- 1

- 1,110
- 1
- 9
- 17
Set the image to the background of the button. Then the title should be visible.
If you still need to place an Label on the Button, you can add Auto Layout constraints in code. They work in this situation.
Edit: Example in Swift to be used in a Playground:
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)

- 13,975
- 2
- 47
- 58
-
this works..but i need an update on this..i mean, can I increase the the number of lines of title, like I can set in a UILabel so that the contents don't go beyond the boundaries of the button? – Sidharth J Dev Apr 22 '15 at 09:54
-
1Set the `numberOfLines` property of the textLabel of the button to 0 and make the button big enough. – dasdom Apr 22 '15 at 09:59
In this scenario, i would suggest create your own custom view.
Create a view and include a label and a uiimageview as subviews
RootView:
++++++++++++
UIImageView
----------------------
UILabel
++++++++++++
Then you can add tapgesture to the rootview to simulate the button behavior.

- 17
- 1