Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 919
Tim J Avatar asked May 24 '19 14:05

Tim J


2 Answers

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
like image 154
Alastar Avatar answered Dec 18 '22 02:12

Alastar


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.

like image 39
user1994956 Avatar answered Dec 18 '22 04:12

user1994956