I watch an awful lot of videos of people programming. I find it both relaxing and interesting. Once such set of videos I enjoy watching are those produced by Brian Voong, who posts YouTube iOS walk-throughs under the title of “Let’s Build That App”.
I happened to have one of his videos running on my second monitor while I was coding and my ears pricked up when he started speaking about a helper extension he was using (and I assume also created) that took away some of the verbose boilerplate code that you need to write when creating Auto Layout constraints programmatically using the visual formatting language (VFL). Now this may not be useful if you need to add additional NSLayoutFormatOptions beyond the defaults but for the majority of use cases this is very handy.
To that end I wanted to share the code
- because I think it’s very handy if you do a lot of constraint configuring in code
- and because Brian’s videos are great and you should check them out (regardless of your ability)
So here’s the code:
import UIKit extension UIView { func addConstraintsWithFormat(format: String, views: UIView...) { var viewDictionary = [String: UIView]() for (index, view) in views.enumerated() { let key = "v\(index)" viewDictionary[key] = view view.translatesAutoresizingMaskIntoConstraints = false } self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: format, options: NSLayoutFormatOptions(), metrics: nil, views: viewDictionary)) } }
Here is how you’d implement it within a custom view for example:
self.addConstraintsWithFormat(format: "H:|[v0]|", views: contentView) self.addConstraintsWithFormat(format: "V:|[v0]|", views: contentView)
and here is something slightly more complex…
self.addConstraintsWithFormat(format: "H:|-8-[v0(100)]-8-[v1(>=20)]-8-[v2(100)]-8-|", views: previousButton, pageControl, nextButton)
Pretty clean and compact eh? Anyway I hope you find this useful, and thanks Brian!