UIKit on iOS is great! There are tons of tools and often this can supercharge your productivity for getting a prototype out into the world.
Additionally, working with AutoLayout programmatically can be great if you avoid these rookie mistakes.
Rookie Mistake 1:
It hurts when you spend hours dealing with the rookie mistake of forgetting to set translatesAutoresizingMaskIntoConstraints
to false
on the view when setting constraints.
view.translatesAutoresizingMaskIntoConstraints = false
Rookie Mistake 2:
Remember that you also have to also set your NSLayoutConstraint to true
Example:
yourView.centerXAnchor.constraint(equalTo:
view.centerXAnchor).isActive = true
Solution:
This function allows you to program with wild abandon! If you use this function to set your constraints you never need to remember those pesky settings.
func setLayoutConstraints(
view: UIView,
constraints: [NSLayoutConstraint]) {
view.translatesAutoresizingMaskIntoConstraints = false
constraints.forEach({constraint in
constraint.isActive = true
})
}
*Update: Apple created a convenience method on NSLayoutConstraint
called .activate
that will set the isActive
property to true. The new code would look like this:
func setLayoutConstraints(
view: UIView,
constraints: [NSLayoutConstraint]) {
view.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate(constraints)
}