Search code examples
iosswiftautolayoutnslayoutconstraint

What exactly does lowering the priority of a constraint do?


I am constructing a variable size table view within another view. The table view should not scroll so I am programmatically determining its content size and adjusting a height constraint so that the table view always fits its content.

The problem I run into is a warning about a broken constraint:

Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want. 
Try this: 
    (1) look at each constraint and try to figure out which you don't expect; 
    (2) find the code that added the unwanted constraint or constraints and fix it. 
(Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) 
(
"<NSAutoresizingMaskLayoutConstraint:0x170498b00 h=--& v=--& UIView:0x1024f2c90.height == 322   (active)>",
"<NSLayoutConstraint:0x17428d660 UITableView:0x103152400.height == 322   (active)>",
"<NSLayoutConstraint:0x174482da0 V:[UITableView:0x103152400]-(27)-|   (active, names: '|':UIView:0x1024f2c90 )>",
"<NSLayoutConstraint:0x17429da10 V:|-(16)-[UITableView:0x103152400]   (active, names: '|':UIView:0x1024f2c90 )>"
)

To fix this, I tried 2 things:

  1. Set translatesAutoresizingMaskIntoConstraints = false. This causes everything to go haywire with the table view.
  2. Lower the priority of the adjustable height constraint to 999.

Point 2 solves my problem and I'm able to adjust the height of the view using the lower priority constraint. But, I don't understand why this works.

So, how does Auto Layout interpret the priority of a constraint? I would've expected the NSAutoresizingMaskLayoutConstraint to take over the lower priority constraint and make it so I could not resize the view using the constraint.


Solution

  • To answer the question in the headline: Lowering the priority of a constraint tells the autolayout that the constraint is less important than all constraints with a higher priority.

    This means that if two constraints are conflicting autolayout will use the one with the highest priority and disregard the other.

    If two required constraints with identical priorities conflict, you will have an error message like the one you describe.