SphynxTech
SphynxTech

Reputation: 1849

Initialize a button with a title from a Label in swift

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

Upvotes: 0

Views: 5986

Answers (3)

ronatory
ronatory

Reputation: 7324

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

Upvotes: 3

user4886069
user4886069

Reputation:

if let textFromLabel = yourCustomLabel.text {

    yourButton.setTitle(textFromLabel, .normal)
}

is what I'll suggest you to do

Upvotes: 0

Yannick
Yannick

Reputation: 3278

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)

Upvotes: 0

Related Questions