iosswiftautolayouthamburger-menu

Update layout constraints programmatically without IBOutlets - Swift


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?


Solution

  • 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()
        }
    }