Search code examples
swiftuikit

Changing constraints by pressing a button


Is there a way to change view’s centerXAnchor constraint to another object (with animation) by pressing a button while the app is running?

Thank's for all of the answers!


Solution

  • First, you need to create an IBOutlet for your constraint from the storyboard, something similar to this.

    @IBOutlet weak var centerXConstraint: NSLayoutConstraint!
    

    And when the button is pressed, you should change the constraint value and update the view layout.

    centerXConstraint.constant = setYourValueHere
    UIView.animate(withDuration: 0.3, animations: { 
       self.view.layoutIfNeeded()
    })
    

    If you want to add constraints programmatically, then remove @IBOutlet weak.

    var centerXConstraint: NSLayoutConstraint!
    

    Assign your view's center X anchor to it.

    centerXConstraint = yourView.centerXAnchor.constraint(equalTo: super.view.centerXAnchor, constant: 0)
    centerXConstraint.isActive = true
    

    after that, you can change it as described above.