How to set variations of a NSLayoutConstraint constant in code?

Viewed 619

I have drag and dropped the constraint in my code and can access it.

@IBOutlet weak var betweenTextTerms: NSLayoutConstraint!

Howeever it seems all I can do is set the constant. But how do I set the value for variations such as Compact Regular in code?

enter image description here

1 Answers

To do this programmatically you override traitCollectionDidChange: method in your view controller.

You can then look at self.traitCollection.horizontalSizeClass and self.traitCollection.verticalSizeClass to decide what to do. Use the reference that you have created to the layout constraint to set the constant accordingly.

After all of your layout constraints are set, call updateConstraints on your view to trigger a layout pass.

For example:

override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
    let hCompact = (self.traitCollection.horizontalSizeClass == .compact)
    let vRegular = (self.traitCollection.verticalSizeClass == .regular)

    if hCompact && vRegular {
        self.betweenTextTerms.constant = 45
    }

    self.updateViewConstraints()
}

For simple cases, it is much more convenient to do this in the Storyboard!

Related