Hacker News new | ask | show | jobs
by melling 2353 days ago
Instead of this format,

    Col.topAnchor.constraint(equalTo: topAnchor, constant: 0).isActive = true           
    Col.bottomAnchor.constraint(equalTo: bottomAnchor, constant: 0).isActive = true
    Col.leftAnchor.constraint(equalTo: leftAnchor, constant: 0).isActive = true
    Col.rightAnchor.constraint(equalTo: rightAnchor, constant: 0).isActive = true
I prefer:

NSLayoutConstraint.activate([

    Col.topAnchor.constraint(equalTo: topAnchor, constant: 0), 
    Col.bottomAnchor.constraint(equalTo: bottomAnchor, constant: 0),  
    Col.leftAnchor.constraint(equalTo: leftAnchor, constant: 0),      
    Col.rightAnchor.constraint(equalTo: rightAnchor, constant: 0),
])

GitHub example with better readability:

https://github.com/melling/ios_topics/tree/master/ButtonCent...

3 comments

Not only is this easier to read (IMO), but it is typically "more efficient than activating each constraint individually": https://developer.apple.com/documentation/uikit/nslayoutcons...
It is easier to read but harder to debug. If you activate all constraints at the same time and something goes wrong you end up with an exception at activateConstraints. Then you would have to figure out which constraint is the cause of the exception. If you activate the constraints one by one then you will get much more helpful exceptions.

The rule that I followed was:

Use activateConstraints if you actually have a performance problem and otherwise activate constraints one by one.

However since this is a framework this rule may not apply because you don't know how it will be used.

Why not just use a wrapper function taking in an array that activates one-by-one in debug and as a group in release builds?
Great idea IMO and wouldn't be difficult to whip up - fighting urge to add to this my native iOS projects right now...
I definitely would try this out, it’s nice to hear some advice too. Thanks!
Enforcing the `NSLayoutConstraint.activate(_:)` API for this in my codebase has saved so much debugging of stupid errors.

All it takes is forgetting to add `.isActive = true` to a single constraint and nothing will work, and it can be so difficult to spot.

Hacker News ate your formatting. Perhaps you could revisit it and clean it up a little?