0

I want to initialize a button's title from a Label. I have this code:

let smallSquare = CGSize(width: 30, height: 30)
let button = UIButton(frame: CGRect(origin: CGPointZero, size: smallSquare))

But, I do not know how I can initialize a title with my label:

let label = UILabel(frame: CGRectMake(0, 0, 200, 21))
label.center = CGPointMake(160, 284)
label.textAlignment = NSTextAlignment.Center
label.text = "I'am a test label"

Normally, I use this property to add a title with a string:

button.setTitle("Button Title",for: .normal)

Is it possible to simply put my Label in my button's title?

Thanks in advance

ronatory
  • 7,156
  • 4
  • 29
  • 49
SphynxTech
  • 1,799
  • 2
  • 18
  • 38

3 Answers3

3

You can add you custom label as subview to your button like Mike Alter mentioned in the comments like this (Note: Code is in Swift 3, but should be easy to adopt to Swift 2.*. Hints are in the code comments):

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .white

        let smallSquare = CGSize(width: 30, height: 30)
        let button = UIButton(frame: CGRect(origin: .zero, size: smallSquare))
        button.translatesAutoresizingMaskIntoConstraints = false
        button.backgroundColor = .red

        // add the button to your view
        view.addSubview(button)

        // set constraints of your button
        button.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        button.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true


        let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 21))
        label.translatesAutoresizingMaskIntoConstraints = false
        label.center = CGPoint(x: 160, y: 284)
        label.textAlignment = .center
        label.text = "I'm a test label"

        // add the label to your button
        button.addSubview(label)

        // set constraints of your label
        label.centerXAnchor.constraint(equalTo: button.centerXAnchor).isActive = true
        label.centerYAnchor.constraint(equalTo: button.centerYAnchor).isActive = true
    }
}

Result with your custom values looks like this (Just added the red background of the button so you see the frame of the button compared to the label frame):

enter image description here

ronatory
  • 7,156
  • 4
  • 29
  • 49
0

Your label has a text property. You used it to set a value and you can also use it to get the value. The text is optional, so you need to unwrap.

let labelText = label.text ?? ""
button.setTitle(labelText, for: .normal)
Yannick
  • 3,210
  • 1
  • 21
  • 30
0
if let textFromLabel = yourCustomLabel.text {

    yourButton.setTitle(textFromLabel, .normal)
}

is what I'll suggest you to do