Skip to content

Instantly share code, notes, and snippets.

@GregIngelmo
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save GregIngelmo/485c681425b8aaaa8025 to your computer and use it in GitHub Desktop.
Save GregIngelmo/485c681425b8aaaa8025 to your computer and use it in GitHub Desktop.
NSLayoutConstraint playground test
// how to programatically create NSLayoutConstraints inside a playground
import UIKit
let viewFrame = CGRect(x: 0, y: 0, width: 640, height: 750)
let view = UIView(frame: viewFrame)
view.backgroundColor = UIColor.greenColor()
// initially the subView will obscure the entire view
let subView = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.Dark))
subView.backgroundColor = UIColor.redColor()
view.addSubview(subView)
// Align the top of the subView to the top of its parent view
let topConstraint = NSLayoutConstraint(
item: subView,
attribute: NSLayoutAttribute.Top,
relatedBy: NSLayoutRelation.Equal,
toItem: subView.superview,
attribute: NSLayoutAttribute.Top,
multiplier: 1,
constant: 0
)
// Align the leading (left) edge to the leading (left) edge of its parent view
let leadingConstraint = NSLayoutConstraint(
item: subView,
attribute: NSLayoutAttribute.Leading,
relatedBy: NSLayoutRelation.Equal,
toItem: subView.superview,
attribute: NSLayoutAttribute.Leading,
multiplier: 1,
constant: 0
)
// Align the trailing (right) edge to the trailing (right) edge of its partent view
let trainlingConstraint = NSLayoutConstraint(
item: subView,
attribute: NSLayoutAttribute.Trailing,
relatedBy: NSLayoutRelation.Equal,
toItem: subView.superview,
attribute: NSLayoutAttribute.Trailing,
multiplier: 1,
constant: 0
)
// Give the subView a constant height of 64 points. Not the special "NotAnAttribute"
let heightConstraint = NSLayoutConstraint(
item: subView,
attribute: NSLayoutAttribute.Height,
relatedBy: NSLayoutRelation.Equal,
toItem: nil,
attribute: NSLayoutAttribute.NotAnAttribute,
multiplier: 1,
constant: 64
)
subView.setTranslatesAutoresizingMaskIntoConstraints(false)
view.addConstraint(topConstraint)
view.addConstraint(leadingConstraint)
view.addConstraint(trainlingConstraint)
view.addConstraint(heightConstraint)
// This is necessary to force autolayout to reposition the views
view.layoutIfNeeded()
view
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment