Skip to content

Instantly share code, notes, and snippets.

@algal
Created July 14, 2015 23:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save algal/a9a59f4fcf23f9051031 to your computer and use it in GitHub Desktop.
Save algal/a9a59f4fcf23f9051031 to your computer and use it in GitHub Desktop.
Vertically stacking views
/**
Adds views to containerView, along with constraints to stack them vertically
and fill horozintally.
*/
func addVerticallyStackedViews(views:[UIView], toView containerView:UIView) -> [NSLayoutConstraint]
{
for v in views {
v.setTranslatesAutoresizingMaskIntoConstraints(false)
containerView.addSubview(v)
}
var cs:[NSLayoutConstraint] = []
if let topView = views.first {
cs.append(NSLayoutConstraint(item: containerView, attribute: .Top, relatedBy: .Equal, toItem: topView, attribute: .Top, multiplier: 1.0, constant: 0))
}
if let bottomView = views.last {
cs.append(NSLayoutConstraint(item: containerView, attribute: .Bottom, relatedBy: .Equal, toItem: bottomView, attribute: .Bottom, multiplier: 1.0, constant: 0))
}
let offset = Array(views[1..<views.count])
for (aboveView,belowView) in Zip2(views,offset) {
cs.append(NSLayoutConstraint(item:aboveView,attribute:.Bottom, relatedBy:.Equal, toItem:belowView, attribute:.Top,multiplier:1.0,constant:0))
}
for v in views {
let leftC = NSLayoutConstraint(item: v, attribute: .Left, relatedBy: .Equal, toItem: containerView, attribute: .Left, multiplier: 1, constant: 0)
let rightC = NSLayoutConstraint(item: v, attribute: .Right, relatedBy: .Equal, toItem: containerView, attribute: .Right, multiplier: 1, constant: 0)
cs.append(leftC)
cs.append(rightC)
}
NSLayoutConstraint.activateConstraints(cs)
return cs
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment