IOS constraint style: addConstraints vs .isActive = true

I have code that programmatically creates automatic layout constraints and adds them to the view.

There are two ways to do this: call addConstraints in addConstraints or set .isActive = true for 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 on top of the other? (performance / etc.), or it happens purely to style.

(I don’t think that the restrictions are evaluated until the next layout passes, so I don’t think it is important that we add them one by one, and not in the block?)

If it's just a style, which style is more preferable for the community?

(I personally prefer addConstraints, however it is very close, and I can easily shake .ISActive)

+5
source share
1 answer

According to addConstraint: documentation addConstraint: setting the active property is recommended for individual restrictions. (note: active property is only available on iOS 8 +).

When developing for iOS 8.0 or later, set the active restrictions to the YES property instead of calling the addConstraint: method directly. The active property automatically adds and removes the constraint from the correct view. ( reference )

Also, if you look at the interface definition for addConstraint: it has this comment:

// This method will be deprecated in a future version and should be avoided. Instead, set the NSLayoutConstraint property to YES


With that said, there is actually a 3rd [and probably best] alternative, which is to use the NSLayoutConstraint activate: class method::

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

It is also the recommended solution according to the documentation and interface files. Therefore, if you have several limitations, this would be an easy solution and would probably be preferable in your situation.

(comment on interface, my hit):

A convenience method that activates every constraint in the contained array, in the same way as setting active = YES. This is often more effective than activating each restriction individually.

+14
source

Source: https://habr.com/ru/post/1257909/


All Articles