Using anchors to match a parent view's constraints
Published on · Updated on
1 minute read
Swift extensions are really great, including when working with Auto Layout. We can make a child view fill its superview using constraints, as well as having insets between them. This is very useful when adding a child view controller to its parent within a subview.
extension UIView {
func attachAnchors(to view: UIView, with insets: UIEdgeInsets = .zero) {
NSLayoutConstraint.activate([
topAnchor.constraint(equalTo: view.topAnchor, constant: insets.top),
rightAnchor.constraint(equalTo: view.rightAnchor, constant: -insets.right),
bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -insets.bottom),
leftAnchor.constraint(equalTo: view.leftAnchor, constant: insets.left)
])
}
}
I hope the article was useful. If you have any feedback or questions please feel free to reach out to me on Twitter.
Thanks for reading and happy coding!
Hi, I hope you enjoyed the article. I am Andrew - a builder of apps and developer tools. Articles on the blog focus on all aspects of Android and iOS development using Kotlin and Swift.