Skip to main content

Articles, snippets and thoughts about code from Andrew Lord.

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) {
topAnchor.constraint(equalTo: view.topAnchor, constant:,
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!

Like what you read? Please share the article.

Avatar of Andrew Lord

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.

Subscribe via RSS