7

I'm trying to make a slide out menu by changing the left anchor constraint when the "open" button is tapped. I've seen people do it using IBOutlets on the constrains, but the view I'm working with is made completely programmatically, preventing me from doing that.

The view is initially positioned off the screen, so I thought I could just change the constraint when I tapped the "open" button, but the code below does nothing.

@objc func slideMenu() {
    sideMenu.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0).isActive = true
    view.setNeedsUpdateConstraints()
}

Is there a way to update the left anchor constraint without the IBOutlet?

yambo
  • 1,388
  • 1
  • 15
  • 34

1 Answers1

15

Store the constraint in a variable and change the constant and call layoutIfNeeded when you need it animated.

// Declare this along with the other variables in your class
var constraintVariable: NSLayoutConstraint!

.
.
.

// Where you set your constraints. Store the constraint to be animated in the variable and make it active
// Your other constraints
constraintVariable = sideMenu.leftAnchor.constraint(equalTo: view.leftAnchor, constant: someNegativeValue);
constraintVariable.isActive = true

.
.
.

@objc func slideMenu() {
    UIView.animate(withDuration: suitableDuration) {
        constraintVariable.constant = requiredValue
        view.setNeedsLayout()
        view.layoutIfNeeded()
    }
}
Rakesha Shastri
  • 11,053
  • 3
  • 37
  • 50
  • So do I use the `constraintVariable` to set my initial constraint of the view? The initial constraint that keeps the view off the screen? – yambo Sep 22 '18 at 17:05
  • @yambo check out the second line of code in the answer. You should be able to figure out where if fits. I have provided proper comments too. – Rakesha Shastri Sep 22 '18 at 17:07
  • Sorry for my misunderstanding. In the setup function I have for setting up the initial constraints I set the `leftAnchor` constraint to be off the screen, so that the view is hidden. I've added the line of code to set the `constraintVariable` as your comment says, and changed the @objc function with the code you've provided, but when the button is tapped nothing happens. – yambo Sep 22 '18 at 17:18
  • @yambo ah i got it. When you set the constraint. Set the constant value as some negative value like you have it right now. Except, instead of setting it as active, **store** it in a variable and use that variable to set it as active. – Rakesha Shastri Sep 22 '18 at 17:20
  • Thanks! Sorry again for the misunderstanding. This works perfectly – yambo Sep 22 '18 at 17:39