Tim J
Tim J

Reputation: 1271

Programmatically set constraint priority

I have a requirement to recreate a .xib based layout programmatically.

I have largely been able to achieve this, however, cannot set the priority of one of my anchors.

The setting I am trying to reproduce in code is:

xib constraints

I thought I could set it using setContentHuggingPriority(.init(999), for: .vertical) but this had no effect.

How can I target this property in code?

Upvotes: 15

Views: 23401

Answers (2)

Alastar
Alastar

Reputation: 1374

You should use a priority lower than 1000, so 999 will be perfect.

let constraint = firstView.widthAnchor.constraint(equalTo: secondView.widthAnchor)
constraint.priority = UILayoutPriority(999)
constraint.isActive = true

Update

You can also use defaultLow instead of specifying the raw value

constraint.priority = .defaultLow

Upvotes: 31

M.Yessir
M.Yessir

Reputation: 222

I know it's super late, but here if it helps someone. So you will need 2 constraints if you want to play with priority.

private var _constraintToManageHQ:NSLayoutConstraint?
_constraintToManageHQ = _viewHBar1.topAnchor.constraint(equalTo: _lblAddress.bottomAnchor, constant: 14.0)
_constraintToManageHQ!.isActive = true
_constraintToManageHQ!.priority = UILayoutPriority(rawValue: 995)

the other constraint with default 1000 priority

_viewHBar1.topAnchor.constraint(equalTo: _containerHeadQuater.bottomAnchor, constant: 14.0).isActive = true

and once _containerHeadQuater.removeFromSuperview() is removed from superview, your _constraintToManageHQ with lower priority kicks in and keeps the UI stable.

Upvotes: 2

Related Questions