I have a button placed in the center using centerXAnchor of superview, but now I have to change the position of the button from centerX to align leading from code. However, it’s not moving to the left. Instead, it gets full width button.
buttonView!.translatesAutoresizingMaskIntoConstraints = false
buttonView!.removeConstraints(buttonView!.constraints)
NSLayoutConstraint.activate([
buttonView!.leadingAnchor.constraint(equalTo: mainView.leadingAnchor, constant: 12),
buttonView!.bottomAnchor.constraint(equalTo: mainView.bottomAnchor, constant: 20),
])
3
Answers
first remove all Constraint
to use it
ref
Removing/add constraints doesn’t cause them to be (re)applied.
Call
.setNeedsUpdateConstraints()
on your view. The system will then callupdateConstraints
as part of its next layout pass. For complex constraint scenarios you may need your own implementation ofupdateConstraints
, but for most cases, and definitely yours, this won’t be needed (and should generally be avoided unless there is a specific reason to use it – see the docs)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:
Priority: Required (1000)
Priority: Low (250)
Connect them to outlets:
Then, to switch from centered to leading:
and you can "toggle" it back to centered with:
Perhaps do the same thing with centerY and bottom constraints.
If you want a little more "flexibility," you could do something like this:
Then, to change that to a leading constraint:
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.