Search code examples
swiftautolayoutconstraints

How can I change certain constraint parameters with programmatically?


Can I change "top space to" constraint, equals parameter with programmatically?

Top Space to Equals is 15 in photo. Can I change this with 100?

enter image description here


Solution

  • Yes, connect the constraint to an outlet like:

    @IBOutlet var constraintTop: NSLayoutConstraint!
    

    Select the constraint in the storyboard and connect it as you would connect any other UI element.

    1. Select ViewController and right-click drag to the constraint
      1

    2. Release click and select contraintTop
      2

    Then you can programmatically update it:

    constraintTop.constant = 100
    self.view.layoutIfNeeded()
    

    NOTE: Here layoutIfNeeded() is called on self.view because the constraint is owned by self.view.
    In nested views, as an optimization, you could layout only the view that needs to be updated.
    So suppose this constraint was in some other view, say myView, then you would do myView.layoutIfNeeded()