Skip to content

Instantly share code, notes, and snippets.

@damionvega
Last active October 19, 2015 07:37
Show Gist options
  • Save damionvega/cd6054c6cae770713615 to your computer and use it in GitHub Desktop.
Save damionvega/cd6054c6cae770713615 to your computer and use it in GitHub Desktop.
iOS Swift Auto layout - Visual Format Language - for-loop adding multiple constraints
// Resulting code: http://cl.ly/image/0z0H2C230H3R
// the superview, `self.statsView`, just a UIView in my storyboard with a
// trailing/leading constraint of 6, bottom/top constraint of 12 and 60pt height
var redView: UIView!
var blueView: UIView!
var yellowView: UIView!
redView = UIView()
blueView = UIView()
yellowView = UIView()
redView.setTranslatesAutoresizingMaskIntoConstraints(false)
blueView.setTranslatesAutoresizingMaskIntoConstraints(false)
yellowView.setTranslatesAutoresizingMaskIntoConstraints(false)
redView.backgroundColor = UIColor.redColor()
blueView.backgroundColor = UIColor.blueColor()
yellowView.backgroundColor = UIColor.yellowColor()
self.statsView.addSubview(redView)
self.statsView.addSubview(blueView)
self.statsView.addSubview(yellowView)
let views = [
"red": redView,
"blue": blueView,
"yellow": yellowView
]
let metrics = [
"margin": 2
]
view.addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat(
"V:|-margin-[red(>=10)]-margin-[blue(==red)]-margin-[yellow(==red)]-margin-|",
options: nil,
metrics: metrics,
views: views))
for (index, (key, val)) in enumerate(views) {
self.statsView.addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat(
"H:|-60-[\(key)(>=100)]-60-|", options: nil, metrics: nil, views: views))
}
// Or preferrably omit unused values using `_`
for (_, (key, _)) in enumerate(views) {
self.statsView.addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat(
"H:|-60-[\(key)(>=100)]-60-|", options: nil, metrics: nil, views: views))
}
// Another example creating an "inline-block" effect
// Screenshot: http://cl.ly/image/1U1b0F2X0Y1U
let metrics = [
"vSpace": 6,
"hSpace": 12
]
self.statsView.addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat(
"H:|-hSpace-[red]-hSpace-[blue(==red)]-hSpace-[yellow(==red)]-hSpace-|", options: nil, metrics: metrics, views: views))
for (_, (key, _)) in enumerate(views) {
self.statsView.addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat(
"V:|-vSpace-[\(key)]-vSpace-|", options: nil, metrics: metrics, views: views))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment