Categories
autolayout ios nslayoutconstraint swift

iOS constraint style: addConstraints vs .isActive = true

I have some code which is creating auto-layout constraints programatically, and adding them to a view.

There are two ways to do this – call addConstraints on the superView, or set .isActive = true on each constraint (which internally calls addConstraint)

Option 1:

parent.addConstraints([
child.topAnchor.constraint(equalTo: parent.topAnchor, constant: 20),
child.leftAnchor.constraint(equalTo: parent.leftAnchor, constant: 5) ])

Option 2:

child.topAnchor.constraint(equalTo: parent.topAnchor, constant: 20).isActive = true
child.leftAnchor.constraint(equalTo: parent.leftAnchor, constant: 5).isActive = true

My question is, is there any benefit to doing one over the other? (performance/etc) or does it come purely down to style.

(I don’t think constraints are evaluated until the next layout pass, so I don’t think it should matter that we add them one-by-one instead of in a block??)

If it is just style, what’s the “more preferred” style by the community??

(personally I prefer addConstraints, however it’s very close and I could be easily swayed to .isActive)