Created
July 14, 2015 23:04
-
-
Save algal/a9a59f4fcf23f9051031 to your computer and use it in GitHub Desktop.
Vertically stacking views
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
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