DonaldlWu
8/8/2017 - 3:25 PM

addNewLabelIntoButton.swift

import UIKit

class ViewController: UIViewController {
    
    // Create New Button
    let newButton: UIButton = {
        let button = UIButton()
        button.translatesAutoresizingMaskIntoConstraints = false
        button.setTitle("ButtonOne", for: .normal)
        button.backgroundColor = .red
        return button
    }()
    
    // Create New Label
    let insertLabel: UILabel = {
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.text = "New Label"
        label.backgroundColor = .blue
        label.textAlignment = .center
        return label
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Add button into view
        view.addSubview(newButton)
        
        // button Layout(on view)
        newButton.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
        newButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        newButton.widthAnchor.constraint(equalToConstant: 200).isActive = true
        newButton.heightAnchor.constraint(equalToConstant: 200).isActive = true
        
        // Add label into button
        newButton.addSubview(insertLabel)
        
        // Label Layout(on newButton p.s. view == newButton)
        insertLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 40).isActive = true
        insertLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        insertLabel.widthAnchor.constraint(equalToConstant: 100).isActive = true
        insertLabel.heightAnchor.constraint(equalToConstant: 50).isActive = true
    }

}