Last active
February 1, 2016 10:30
-
-
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.
This file contains 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
//Add constraint with top left right bottom is (0, 0, 0, 0) | |
func addChildToContainer(parent container: UIView, child childView: UIView) { | |
container.addSubview(childView) | |
childView.translatesAutoresizingMaskIntoConstraints = false | |
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 addChildToContainer(parent container: UIView, child childView: UIView, andInsets insets: UIEdgeInsets) { | |
container.addSubview(childView) | |
childView.translatesAutoresizingMaskIntoConstraints = false | |
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