Created
March 22, 2017 12:36
-
-
Save antonyalkmim/e67fecc76c845d3573edd50637789263 to your computer and use it in GitHub Desktop.
iOS AutoLayout Extensions with NSLayoutAnchor
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
// 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