Search code examples
iosswiftconstraintsnslayoutconstraintnslayoutanchor

Update widthAnchor on Device orientation


I have this constraint in my controller for a view like this:

someView.widthAnchor.constraint(equalToConstant: view.bounds.width).isActive = true

Now I've added this constraint in willLayoutSubviews to update it on device rotation.

But it doesn't seem to update, even more like it adds another width constraint, which of course conflicts with the old width constraint.

Now I don't really know a proper solution to update this width constraint, but it seems to me like I need to remove the constraint first and then set it again.

Which if I test this like this:

someView.constraints.forEach {
    someView.removeContraint($0)
}

This works like expected, only it deletes of course some constraints I don't want to delete... so also not a solution.


Solution

  • Sol1

    hook the width constraint as IBOutlet and change it's constant in code like this

    self.widthCon.constant = //value
    self.view.layoutIfNeeded()
    

    Sol2

    delete the constraint with identifier

    someView.constraints.forEach {
       if $0.identifier == "set_id" {
          someView.removeConstraint($0)
          someView.widthAnchor.constraint(equalToConstant: view.bounds.width).isActive = true
       }
    }