Skip to content

Instantly share code, notes, and snippets.

@MaherKSantina
Last active October 22, 2019 06:18
Show Gist options
  • Save MaherKSantina/a847797eb1856817421d674dd1f8c75f to your computer and use it in GitHub Desktop.
Save MaherKSantina/a847797eb1856817421d674dd1f8c75f to your computer and use it in GitHub Desktop.
This gist helps with placing views inside each other using autolayout constraints
public typealias ConstraintsConfiguration = (_ top: NSLayoutConstraint, _ left: NSLayoutConstraint, _ bottom: NSLayoutConstraint, _ right: NSLayoutConstraint) -> Void
extension UIView {
/**
Embeds a subview inside the current view and adds constraints to fit the subview in the whole view. An optional constraints configuration closure can be specified to do extra customization for the added constraints, or you can keep a reference for the added constraints in this closure.
- Parameter subview: The subview that will be added
- Parameter constraintsConfiguration: The constraint configuration that will be applied to the newly added constraints
*/
public func addSubviewWithConstraints(_ subview: UIView, constraintsConfiguration: ConstraintsConfiguration? = nil) {
// Required to disable auto generation of constraints
subview.translatesAutoresizingMaskIntoConstraints = false
// Create a top, left, bottom and right constraints
let viewConstraints = [NSLayoutConstraint.Attribute.top,
NSLayoutConstraint.Attribute.left,
NSLayoutConstraint.Attribute.bottom,
NSLayoutConstraint.Attribute.right].map { (attribute) -> NSLayoutConstraint in
return NSLayoutConstraint(item: subview, attribute: attribute, relatedBy: .equal, toItem: self, attribute: attribute, multiplier: 1, constant: 0)
}
// Insert subview in view
addSubview(subview)
// Apply constraints
addConstraints(viewConstraints)
// Call closure to configure constraints
constraintsConfiguration?(viewConstraints[0], viewConstraints[1], viewConstraints[2], viewConstraints[3])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment