How to update swift Layout Anchors?

swift update constraints programmatically
translatesautoresizingmaskintoconstraints
nslayoutanchor swift 4
nslayoutconstraint
add constraints programmatically swift 4
swift remove anchor constraint
swift unable to activate constraint with anchors
widthanchor swift

Trying to find a solution to update multiple constraints for multiple UI elements on an event. I have seen some examples of deactivating, making a change, then reactivating constraints, this method seems impractical for the 24 anchors I am working with.

One of my sets of changes:

ticketContainer.translatesAutoresizingMaskIntoConstraints = false
ticketContainer.topAnchor.constraintEqualToAnchor(self.topAnchor).active = true
ticketContainer.leftAnchor.constraintEqualToAnchor(self.rightAnchor, constant: 20).active = true
ticketContainer.widthAnchor.constraintEqualToConstant(200.0).active = true

ticketContainer.leftAnchor.constraintEqualToAnchor(self.leftAnchor, constant: 20).active = true
ticketContainer.widthAnchor.constraintEqualToConstant(100.0).active = true

Have you tried saving the relevant constraints you created using the layout anchors to properties, and then just changing the constant? E.g.

var ticketTop : NSLayoutConstraint?

func setup() {
    ticketTop = ticketContainer.topAnchor.constraintEqualToAnchor(self.topAnchor, constant:100)
    ticketTop.active = true
}

func update() {
    ticketTop?.constant = 25
}
Possibly More Elegant

Depending on your taste for writing extensions, here is a possibly more elegant approach that doesn't use properties, but instead creates extension methods on NSLayoutAnchor and UIView to aid in more succinct usage.

First you would write an extension on NSLayoutAnchor like this:

extension NSLayoutAnchor {
    func constraintEqualToAnchor(anchor: NSLayoutAnchor!, constant:CGFloat, identifier:String) -> NSLayoutConstraint! {
        let constraint = self.constraintEqualToAnchor(anchor, constant:constant)
        constraint.identifier = identifier
        return constraint
    }
}

This extension allows you to set an identifier on the constraint in the same method call that creates it from an anchor. Note that Apple documentation implies that XAxis anchors (left, right, leading, etc.) won't let you create a constraint with YAxis anchors (top, bottom, etc.), but I don't observe this to actually be true. If you did want that type of compiler checking, you would need to write separate extensions for NSLayoutXAxisAnchor, NSLayoutYAxisAnchor, and NSLayoutDimension (for width and height constraints) that enforce the same-axis anchor type requirement.

Next you would write an extension on UIView to get a constraint by identifier:

extension UIView {
    func constraint(withIdentifier:String) -> NSLayoutConstraint? {
        return self.constraints.filter{ $0.identifier == withIdentifier }.first
    }
}

With these extensions in place, your code becomes:

func setup() {
    ticketContainer.topAnchor.constraintEqualToAnchor(anchor: self.topAnchor, constant:100, identifier:"ticketTop").active = true
}

func update() {
    self.constraint(withIdentifier:"ticketTop")?.constant = 25
}

Note that using constants or an enum instead of magic string names for the identifiers would be an improvement over the above, but I'm keeping this answer brief and focused.

Layout Anchors, Auto Layout has undergone quite a lot of changes and improvements over the years, in particular with the introduction of layout anchors in iOS� Auto Layout has undergone quite a lot of changes and improvements over the years, in particular with the introduction of layout anchors in iOS 9. Let’s take a look at how they work. Weekly Swift articles, podcasts and tips by John Sundell .


You can iterate over a view's constraints and check for matching items and anchors. Remember that the constraint will be on the view's superview unless it is a dimension constraint. I wrote some helper code that will allow you to find all constraints on one anchor of a view.

import UIKit

class ViewController: UIViewController {

    let label = UILabel()
    let imageView = UIImageView()

    override func viewDidLoad() {
        super.viewDidLoad()

        label.text = "Constraint finder"

        label.translatesAutoresizingMaskIntoConstraints = false
        imageView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(label)
        view.addSubview(imageView)

        label.topAnchor.constraint(equalTo: view.topAnchor, constant: 30).isActive = true
        label.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 20).isActive = true
        label.widthAnchor.constraint(greaterThanOrEqualToConstant: 50).isActive = true

        imageView.topAnchor.constraint(equalTo: label.bottomAnchor).isActive = true
        imageView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 60).isActive = true
        imageView.widthAnchor.constraint(equalTo: label.widthAnchor).isActive = true
        imageView.heightAnchor.constraint(equalToConstant: 70).isActive = true

        print("Label's top achor constraints: \(label.constraints(on: label.topAnchor))")
        print("Label's width achor constraints: \(label.constraints(on: label.widthAnchor))")
        print("ImageView's width achor constraints: \(imageView.constraints(on: imageView.widthAnchor))")
    }

}

public extension UIView {

    public func constraints(on anchor: NSLayoutYAxisAnchor) -> [NSLayoutConstraint] {
        guard let superview = superview else { return [] }
        return superview.constraints.filtered(view: self, anchor: anchor)
    }

    public func constraints(on anchor: NSLayoutXAxisAnchor) -> [NSLayoutConstraint] {
        guard let superview = superview else { return [] }
        return superview.constraints.filtered(view: self, anchor: anchor)
    }

    public func constraints(on anchor: NSLayoutDimension) -> [NSLayoutConstraint] {
        guard let superview = superview else { return [] }
        return constraints.filtered(view: self, anchor: anchor) + superview.constraints.filtered(view: self, anchor: anchor)
    }

}

extension NSLayoutConstraint {

    func matches(view: UIView, anchor: NSLayoutYAxisAnchor) -> Bool {
        if let firstView = firstItem as? UIView, firstView == view && firstAnchor == anchor {
            return true
        }
        if let secondView = secondItem as? UIView, secondView == view && secondAnchor == anchor {
            return true
        }
        return false
    }

    func matches(view: UIView, anchor: NSLayoutXAxisAnchor) -> Bool {
        if let firstView = firstItem as? UIView, firstView == view && firstAnchor == anchor {
            return true
        }
        if let secondView = secondItem as? UIView, secondView == view && secondAnchor == anchor {
            return true
        }
        return false
    }

    func matches(view: UIView, anchor: NSLayoutDimension) -> Bool {
        if let firstView = firstItem as? UIView, firstView == view && firstAnchor == anchor {
            return true
        }
        if let secondView = secondItem as? UIView, secondView == view && secondAnchor == anchor {
            return true
        }
        return false
    }
}

extension Array where Element == NSLayoutConstraint {

    func filtered(view: UIView, anchor: NSLayoutYAxisAnchor) -> [NSLayoutConstraint] {
        return filter { constraint in
            constraint.matches(view: view, anchor: anchor)
        }
    }
    func filtered(view: UIView, anchor: NSLayoutXAxisAnchor) -> [NSLayoutConstraint] {
        return filter { constraint in
            constraint.matches(view: view, anchor: anchor)
        }
    }
    func filtered(view: UIView, anchor: NSLayoutDimension) -> [NSLayoutConstraint] {
        return filter { constraint in
            constraint.matches(view: view, anchor: anchor)
        }
    }

}

Auto Layout anchors, Every UIView has a set of anchors that define its layouts rules. The most important ones are Duration: 5:37 Posted: Sep 15, 2016 To demonstrate anchors, comment out your existing Auto Layout VFL code and replace it with this: That loops over each of the five labels, setting them to have the same width as our main view, and to have a height of exactly 88 points. We haven’t set top anchors, though, so the layout won’t look correct just yet.


Positioning Single View
extension UIView {
    func add(view: UIView, left: CGFloat, right: CGFloat, top: CGFloat, bottom: CGFloat) {
        
        view.translatesAutoresizingMaskIntoConstraints = false
        self.addSubview(view)

        view.leftAnchor.constraint(equalTo: self.leftAnchor, constant: left).isActive = true
        view.rightAnchor.constraint(equalTo: self.rightAnchor, constant: right).isActive = true
        
        view.topAnchor.constraint(equalTo: self.topAnchor, constant: top).isActive = true
        view.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: bottom).isActive = true
        
    }
}
Usage
headerView.add(view: headerLabel, left: 20, right: 0, top: 0, bottom: 0)

Mastering iOS auto layout anchors programmatically from Swift, Looking for best practices of using layout anchors? Let's learn how to use the iOS autolayout system in the proper way using Swift. you'll get an update about the most important Swift community news, including my articles. Auto Layout in Swift: Writing constraints programmatically Auto Layout constraints allow us to create views that dynamically adjust to different size classes and positions. The constraints will make sure that your views adjust to any size changes without having to manually update frames or positions.


I have found another solution. If you want to change an existing constraint added through Interface Builder you actually need to iterate over the constraints of the superview. This is at least true when you try to change the constant value of alignment constraints.

The below example shows the bottom alignment but I assume the same code would work for leading/trailing/top alignment.

    private func bottomConstraint(view: UIView) -> NSLayoutConstraint {
        guard let superview = view.superview else {
            return NSLayoutConstraint()
        }

        for constraint in superview.constraints {
            for bottom in [NSLayoutConstraint.Attribute.bottom, NSLayoutConstraint.Attribute.bottomMargin] {
                if constraint.firstAttribute == bottom && constraint.isActive && view == constraint.secondItem as? UIView {
                    return constraint
                }

                if constraint.secondAttribute == bottom && constraint.isActive && view == constraint.firstItem as? UIView {
                    return constraint
                }
            }
        }

        return NSLayoutConstraint()
    }

NSLayoutAnchor, NSLayoutAnchor. A factory class for creating layout constraint objects using a fluent API. Availability. iOS 9.0+; macOS 10.11+; Mac Catalyst 13.0+; tvOS 9.0+. Mastering iOS auto layout anchors programmatically from Swift Looking for best practices of using layout anchors? Let's learn how to use the iOS autolayout system in the proper way using Swift.


widthAnchor, widthAnchor. A layout anchor representing the width of the view's frame. Availability. iOS 9.0+; Mac Catalyst 13.0+; tvOS 9.0+. Framework. UIKit. On This Page. Auto Layout anchors make it easy to position your views relative to others. There are lots of anchors to choose from: leading and trailing edges, top and bottom edges, center X and center Y, and more. To try it out, first create a view something like this:


Pain Free Constraints with Layout Anchors, Fortunately iOS 9 has done a lot to improve things. Auto Layout Guide: You have three choices when it comes to programmatically creating constraints: You can use layout anchors, you can use Last updated: Jun 12, 2020� Working With Auto Layout And Layout Anchors. working-with-auto-layout-and-layout-anchors. Creating layout constraints in code isn't pretty. It isn't always intuitive and it's verbose, even if you decide to use Apple's Visual Format Language.


Working With Auto Layout and Layout Anchors, Last Updated on Jan 29, 2019. Swift 4 Xcode 10 iOS 12 Instead, you obtain a reference to a layout anchor from the UIView or NSView you're� Layout Anchors. The NSLayoutAnchor class provides a fluent interface for creating constraints. To use this API, access the anchor properties on the items you want to constrain. For example, the view controller’s top and bottom layout guides have topAnchor, bottomAnchor, and heightAnchor properties. Views, on the other hand, expose anchors for