Reputation: 4302
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?
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.
Upvotes: 4
Views: 1845
Reputation: 12324
Yes it is! You can use the document outline view to find the constraint you want to use as a variable. Once you have it, CTRL + Drag from the constraint in the document outline view to your code to make the outlet. Then you can change the constraints in code by using self.constraint.constant = 31
.
To space all the views out equally, you can put UILayoutGuides
in between each of the labels and constrain all their heights to be equal. Then you can change the height of one of the layout guides and they will all change to match it.
Upvotes: 0
Reputation: 154583
The NSLayoutContraint
s 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:
Here it is in action:
Upvotes: 2