Skip to content

Instantly share code, notes, and snippets.

@vienvu89
Last active February 1, 2016 10:30
Show Gist options
  • Select an option

  • Save vienvu89/6599f56577831533b22a to your computer and use it in GitHub Desktop.

Select an option

Save vienvu89/6599f56577831533b22a to your computer and use it in GitHub Desktop.
Sometimes when add child view controller programmatically and just add subview fill all container. You have to add constraint again and again. This snip set code will help you add by one line of code.
//Add constraint with top left right bottom is (0, 0, 0, 0)
func addConstraintsChildToContainer(parent container: UIView, child childView: UIView) {
container.addSubview(childView)
let views = Dictionary(dictionaryLiteral: ("childView", childView),("container", container))
//Horizontal constraints
let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|[childView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)
container.addConstraints(horizontalConstraints)
//Vertical constraints
let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[childView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)
container.addConstraints(verticalConstraints)
}
//Add constraint with top left right bottom is same with option UIEdgeInsets
func addConstraintsChildToContainer(parent container: UIView, child childView: UIView, andInsets insets: UIEdgeInsets) {
container.addSubview(childView)
let views = Dictionary(dictionaryLiteral: ("childView", childView),("container", container))
//Horizontal constraints
let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|-\(insets.left)-[childView]-\(insets.right)-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)
container.addConstraints(horizontalConstraints)
//Vertical constraints
let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|-\(insets.top)-[childView]-\(insets.bottom)-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)
container.addConstraints(verticalConstraints)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment