When programmatically creating layouts, I follow Apple\'s advice: override -updateConstraints, add custom constraints, and call -setNeedsUpdateConstraints once subviews have
Short answer: Potential solution number 2.
Removing and reapplying all constraints may become costly as the layout becomes more complex. Besides, if your layout is stateful, you'd have more problems.
Doubling constraints is very inefficient, you can never know how many times updateConstraints
might be called.
As this blog post shows, using a flag is the simplest, most efficient way of dealing with this problem. That is how I deal with it myself.
As a side note, you mention of there existing an awesome way that you have not thought of yet. Most of the times, the simplest way IS the most awesome way. :)
This kind of tracking could be done too, for the initial setup. In most cases.
override func updateConstraints() {
if constraints.count == 0 {
let views = ["textField": textField]
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[textField]-0-|", options: [], metrics: nil, views: views))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[textField]-0-|", options: [], metrics: nil, views: views))
}
super.updateConstraints()
}