Ryan Francesconi Ryan Francesconi - 5 months ago 9
Swift Question

Simple NSLayoutContraint usage in Swift?

I'm looking for a simple Swift solution for a child view to programmatically fill a super view using NSLayoutContraint. It should be easy to understand. I feel like most of the answers on here currently are more complex than needed.

Rob Rob
Answer

Assuming that you've already set translatesAutoresizingMaskIntoConstraints to false and added subview as a subview of view, you can set the four constraints, like so:

NSLayoutConstraint.activateConstraints([
    subview.leadingAnchor.constraintEqualToAnchor(view.leadingAnchor),
    subview.trailingAnchor.constraintEqualToAnchor(view.trailingAnchor),
    subview.topAnchor.constraintEqualToAnchor(view.topAnchor),
    subview.bottomAnchor.constraintEqualToAnchor(view.bottomAnchor)
])

Or in Swift 3:

NSLayoutConstraint.activate([
    subview.leadingAnchor.constraint(equalTo: view.leadingAnchor),
    subview.trailingAnchor.constraint(equalTo: view.trailingAnchor),
    subview.topAnchor.constraint(equalTo: view.topAnchor),
    subview.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])