Skip to content

Instantly share code, notes, and snippets.

@derekli66
Created June 27, 2018 06:18
Show Gist options
  • Save derekli66/7af7c956f8afc36553830080e917aded to your computer and use it in GitHub Desktop.
Save derekli66/7af7c956f8afc36553830080e917aded to your computer and use it in GitHub Desktop.
Centering subview with autolayout in viewcontroller
fileprivate func createCenterConstraints(with subview: UIView) -> [NSLayoutConstraint]
{
var constraints: [NSLayoutConstraint] = [NSLayoutConstraint]()
let views: [String: Any] = ["view": subview, "superview": self.view]
var horizontalOptions = NSLayoutFormatOptions()
horizontalOptions.insert(NSLayoutFormatOptions.alignAllCenterY)
let horizontalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:[superview]-(<=1)-[view]", options: horizontalOptions, metrics: nil, views: views)
var verticalOptions = NSLayoutFormatOptions()
verticalOptions.insert(NSLayoutFormatOptions.alignAllCenterX)
let verticalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:[superview]-(<=1)-[view]", options: verticalOptions, metrics: nil, views: views)
constraints.append(contentsOf: horizontalConstraints)
constraints.append(contentsOf: verticalConstraints)
return constraints
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment