There are various ways to do this, depending on exactly what you need to accomplish.
First, you said you're laying out your views in Storyboard, so...
If we're talking about one (or a few) specific views, we can create @IBOutlet
vars for the constraints you want to change.
In Storyboard:
- give your buttonView a centerX constraint, with
Priority: Required (1000)
- give your buttonView your desired leading constraint, with
Priority: Low (250)
Connect them to outlets:
@IBOutlet var buttonCenterConstraint: NSLayoutConstraint!
@IBOutlet var buttonLeadingConstraint: NSLayoutConstraint!
Then, to switch from centered to leading:
buttonCenterConstraint.priority = .defaultLow
buttonLeadingConstraint.priority = .required
and you can "toggle" it back to centered with:
buttonLeadingConstraint.priority = .defaultLow
buttonCenterConstraint.priority = .required
Perhaps do the same thing with centerY and bottom constraints.
If you want a little more "flexibility," you could do something like this:
- in Storyboard, set only the centerX constraint
Then, to change that to a leading constraint:
// find the centerX constraint and de-activate it
if let cxConstraint = mainView.constraints.first(where: { ($0.firstAttribute == .centerX && $0.firstItem === buttonView) }) {
cxConstraint.isActive = false
} else if let cxConstraint = mainView.constraints.first(where: { ($0.firstAttribute == .centerX && $0.secondItem === buttonView) }) {
cxConstraint.isActive = false
}
// add a new leading constraint
buttonView.leadingAnchor.constraint(equalTo: mainView.leadingAnchor, constant: 12.0).isActive = true
You could also use an extension as suggested by someone else to "remove all constraints" ... but you risk removing constraints that you do not want changed.