swiftlabelstackview

Cannot change label position in stackview swift


I want to change X position of a label inside a stackview, there is a button inside the stackview as well. However, I am not able to change the label's position as once I set constraints for the label, errors jump out and want me to delete the constraints.


Solution

  • This is an example of a stackview with a button and a label with changes to the label's x position.

    import UIKit
    
    class ViewController: UIViewController {
    
        let stackView = UIStackView()
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            stackView.axis = .vertical
            stackView.distribution = .equalSpacing
            stackView.alignment = .center
    
            view.addSubview(stackView)
            stackView.translatesAutoresizingMaskIntoConstraints = false
            stackView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
            stackView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
            stackView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
            stackView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
    
            let button = UIButton()
            button.setTitle("Button", for: .normal)
            button.setTitleColor(UIColor.black, for: .normal)
            button.backgroundColor = UIColor.lightGray
            stackView.addArrangedSubview(button)
            button.translatesAutoresizingMaskIntoConstraints = false
            button.leftAnchor.constraint(equalTo: stackView.leftAnchor).isActive = true
            button.rightAnchor.constraint(equalTo: stackView.rightAnchor).isActive = true
    
            let label = UILabel()
            label.text = "Label"
            label.textColor = UIColor.black
            label.backgroundColor = UIColor.lightGray
            stackView.addArrangedSubview(label)
            label.translatesAutoresizingMaskIntoConstraints = false
            // Modify left/right anchor constraints for label x position
            label.leftAnchor.constraint(equalTo: stackView.leftAnchor, constant: 24).isActive = true
            label.rightAnchor.constraint(equalTo: stackView.rightAnchor).isActive = true
        }
    
    }