Skip to main content

Using anchors to match a parent view's constraints

Updated:

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.

Thanks for reading!

Like what you read? Please share the article.

Avatar of Andrew Lord

WRITTEN BY

Andrew Lord

A software developer and tech leader from the UK. Writing articles that focus on all aspects of Android and iOS development using Kotlin and Swift.

Want to read more?

Here are some other articles you may enjoy.