Skip to content

Instantly share code, notes, and snippets.

@antonyalkmim
Created March 22, 2017 12:36
Show Gist options
  • Save antonyalkmim/e67fecc76c845d3573edd50637789263 to your computer and use it in GitHub Desktop.
Save antonyalkmim/e67fecc76c845d3573edd50637789263 to your computer and use it in GitHub Desktop.
iOS AutoLayout Extensions with NSLayoutAnchor
// MARK - UIView + Constraints
extension UIView {
@discardableResult func topAnchor(equalTo anchor: NSLayoutYAxisAnchor, constant: CGFloat = 0) -> Self {
topAnchor.constraint(equalTo: anchor, constant: constant).isActive = true
return self
}
@discardableResult func bottomAnchor(equalTo anchor: NSLayoutYAxisAnchor, constant: CGFloat = 0) -> Self {
bottomAnchor.constraint(equalTo: anchor, constant: constant).isActive = true
return self
}
@discardableResult func leadingAnchor(equalTo anchor: NSLayoutXAxisAnchor, constant: CGFloat = 0) -> Self {
leadingAnchor.constraint(equalTo: anchor, constant: constant).isActive = true
return self
}
@discardableResult func trailingAnchor(equalTo anchor: NSLayoutXAxisAnchor, constant: CGFloat = 0) -> Self {
trailingAnchor.constraint(equalTo: anchor, constant: constant).isActive = true
return self
}
@discardableResult func heightAnchor(equalTo height: CGFloat) -> Self {
heightAnchor.constraint(equalToConstant: height).isActive = true
return self
}
@discardableResult func widthAnchor(equalTo height: CGFloat) -> Self {
widthAnchor.constraint(equalToConstant: height).isActive = true
return self
}
}
// MARK - Example
var label = UILabel(frame: .zero)
phoneLabel
.topAnchor(equalTo: otherLabel.bottomAnchor, constant: defaultMargin)
.leadingAnchor(equalTo: leadingAnchor, constant: defaultMargin)
.trailingAnchor(equalTo: trailingAnchor, constant: defaultMargin)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment