0

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

Yuyutsu
  • 2,509
  • 22
  • 38
Sidharth J Dev
  • 927
  • 1
  • 6
  • 25

4 Answers4

1

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];
manojdeshmane99
  • 206
  • 3
  • 10
0

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

Community
  • 1
  • 1
Mustafa Ibrahim
  • 1,110
  • 1
  • 9
  • 17
0

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)
dasdom
  • 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
  • 1
    Set the `numberOfLines` property of the textLabel of the button to 0 and make the button big enough. – dasdom Apr 22 '15 at 09:59
-1

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.

Ben
  • 17
  • 1