Search code examples
iosswiftconstraintsnslayoutconstraint

Positioning constraints not having any effect


I am trying to code the label in the viewDidLoad function. The label is showing up but the code I am using now is not affecting the positioning. I am trying to code everything in the viewDidLoad function. You can see the screenshot below.

override func viewDidLoad() {
    super.viewDidLoad()

    let backbutton = UILabel()
    backbutton.backgroundColor = UIColor.orange
    backbutton.translatesAutoresizingMaskIntoConstraints = false
    backbutton.widthAnchor.constraint(equalToConstant: 300).isActive = true
    backbutton.heightAnchor.constraint(equalToConstant: 300).isActive = true
    backbutton.centerXAnchor.constraint(equalTo: backbutton.centerXAnchor, constant: 100).isActive = true
    backbutton.centerYAnchor.constraint(equalTo: backbutton.centerYAnchor, constant: 300).isActive = true
    view.addSubview(backbutton)
}

enter image description here


Solution

  • This is how you can align the label into the center of the view,

    let backbutton = UILabel()
    view.addSubview(backbutton)
    
    backbutton.backgroundColor = UIColor.orange
    backbutton.translatesAutoresizingMaskIntoConstraints = false
    backbutton.widthAnchor.constraint(equalToConstant: 300).isActive = true
    backbutton.heightAnchor.constraint(equalToConstant: 300).isActive = true
    backbutton.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: 0).isActive = true
    backbutton.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 0).isActive = true
    

    When you are setting constraints programmatically, make sure you add the view into the super/parent view before applying constraints. Secondly in the below lines, you are telling the backButton label to align its center to itself (i.e, backbutton.centerXAnchor.constraint(equalTo: backbutton.centerXAnchor).

    backbutton.centerXAnchor.constraint(equalTo: backbutton.centerXAnchor, constant: 100).isActive = true
    backbutton.centerYAnchor.constraint(equalTo: backbutton.centerYAnchor, constant: 300).isActive = true
    

    As you want to align it center vertically and horizontally to its parent view so you should set the center constraints equal to parent view as below,

    backbutton.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: 0).isActive = true
    backbutton.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 0).isActive = true
    

    enter image description here