Search code examples
iosxcodeautolayoutinterface-buildernslayoutconstraint

Xcode; Set a autolayout constraint to a defined variable value


Is it possible to define a variable, and set a constraints constant value to that variable?

Thereby making it possible to change many constraints by just changing the variable. I think I saw someone do this directly from interface builder ones?

Constraint of a view, from xcode's interface builder

EDIT:

There is a constraint between each label. I need a method to change all of these constraints, so they get a the same value. Is this possible?

If I use a outlet collection, I will have to iterate through all the constraints, and change the value for each. I'm looking for a method like this:

// SEUDO!!
lineSeperationWidth = 31    // changes all 4 constraints.

multiple similar constraints


Solution

  • The NSLayoutContraints are all separate objects, and Xcode provides no way to set the constant value of multiple constraints with the same variable. The closest you can get is to use an @IBOutlet collection and then use the didSet property observer for your variable holding the common space value to update each of the constraints in the collection.

    Here is an example I created which spaces out the labels based upon a random value that I set to the space property each time the Go button is pressed:

    class ViewController: UIViewController {
    
        @IBOutlet var spacers: [NSLayoutConstraint]!
    
        var space: CGFloat = 20.0 {
            didSet {
                spacers.forEach { $0.constant = space }
            }
        }
    
        override func viewDidLoad() {
            super.viewDidLoad()
        }
    
        @IBAction func spaceOut(sender: AnyObject) {
            // set space to a random value
            space = CGFloat(arc4random_uniform(30)) + 20.0
        }
    
    }
    

    Each of the vertical space constraints between the labels is connected to the @IBOutlet collection spacers. Here is what the Connections Inspector shows:

    connections inspector


    Here it is in action:

    enter image description here