If this is your scenario:
- Your buttons and constraints have been set up in IB, and you wish to change or replace the constraints one by one in code
Then you can set up an IBOutlet for each constraint and do your editing (changing, replacing, or even deactivating them) by name.
@IBOutlet weak var likesConstraintLeading: NSLayoutConstraint!
@IBOutlet weak var likesConstraintTop: NSLayoutConstraint!
@IBOutlet weak var likesConstraintWidth: NSLayoutConstraint!
likesConstraintLeading.isActive = false
likesConstraintTop.constant = 20
likesConstraintWidth.multiplier = 3.5
- Your buttons and constraints have been set up in IB, and you wish to replace the entire constraints set up for a single IBOutlet-named button
You can set up the new set of constraints in code as an array and activate them after removing the old constraints.
@IBOutlet weak var likesConstraintTop: NSLayoutConstraint!
@IBOutlet weak var likesConstraintLeading: NSLayoutConstraint!
@IBOutlet weak var likesConstraintWidth: NSLayoutConstraint!
var newConstraints = [NSLayoutConstraint]()
newConstraints.append(likesButton.leadingAnchor.constraint(equalTo: view.leadingAnchor))
newConstraints.append(likesButton.topAnchor.constraint(equalTo: view.topAnchor, constant: 20))
newConstraints.append(likesButton.widthAnchor.constraint(equalToConstant: 100))
likesConstraintLeading.isActive = false
likesConstraintTop.isActive = false
likesConstraintWidth.isActive = false
NSLayoutConstraint.activate([newConstraints])
Please note - you still need to deactivate things one-by-one because these constraints (except for the width) is added to the control's superview and there are likely many more constraints in it!
- You have buttons set up in IB, but you wish to maintain the one set of constraints through code.
This IMHO is the best setup you can do, because you can still add all of your other constraints through IB and limit your code to what you wish to change.
var startingConstraints = [NSLayoutConstraint]()
var endingConstraints = [NSLayoutConstraint]()
override func viewDidLoad() {
startingConstraints.append(likesButton.leadingAnchor.constraint(equalTo: view.leadingAnchor))
startingConstraints.append(likesButton.topAnchor.constraint(equalTo: view.topAnchor, constant: 20))
startingConstraints.append(likesButton.widthAnchor.constraint(equalToConstant: 100))
endingConstraints.append(likesButton.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 30))
endingConstraints.append(likesButton.topAnchor.constraint(equalTo: view.topAnchor, constant: 40))
endingConstraints.append(likesButton.widthAnchor.constraint(equalToConstant: 80))
NSLayoutConstraint.activate([startingConstraints])
}
func changeConstraints() {
NSLayoutConstraint.deactivate([newConstraints])
NSLayoutConstraint.activate([newConstraints])
}