Rog
Rog

Reputation: 17170

What is NSLayoutConstraint "UIView-Encapsulated-Layout-Height" and how should I go about forcing it to recalculate cleanly?

I have a UITableView running under iOS 8 and I'm using automatic cell heights from constraints in a storyboard.

One of my cells contains a single UITextView and I need it to contract and expand based on user input - tap to shrink/expand the text.

I'm doing this by adding a runtime constraint to the text view and changing the constant on the constraint in response to user events:

-(void)collapse:(BOOL)collapse; {

    _collapsed = collapse;

    if(collapse)
        [_collapsedtextHeightConstraint setConstant: kCollapsedHeight]; // 70.0
    else
        [_collapsedtextHeightConstraint setConstant: [self idealCellHeightToShowFullText]];

    [self setNeedsUpdateConstraints];

}

Whenver I do this, I wrap it in tableView updates and call [tableView setNeedsUpdateConstraints]:

[tableView beginUpdates];

[_briefCell collapse:!_showFullBriefText];

[tableView setNeedsUpdateConstraints];
// I have also tried 
// [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationTop];
// with exactly the same results.

[tableView endUpdates];

When I do this, my cell does expand (and animates whilst doing it) but I get a constraints warning:

2014-07-31 13:29:51.792 OneFlatEarth[5505:730175] 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) 

(

    "<NSLayoutConstraint:0x7f94dced2b60 V:[UITextView:0x7f94d9b2b200'Brief text: Lorem Ipsum i...'(388)]>",

    "<NSLayoutConstraint:0x7f94dced2260 V:[UITextView:0x7f94d9b2b200'Brief text: Lorem Ipsum i...']-(15)-|   (Names: '|':UITableViewCellContentView:0x7f94de5773a0 )>",

    "<NSLayoutConstraint:0x7f94dced2350 V:|-(6)-[UITextView:0x7f94d9b2b200'Brief text: Lorem Ipsum i...']   (Names: '|':UITableViewCellContentView:0x7f94de5773a0 )>",

    "<NSLayoutConstraint:0x7f94dced6480 'UIView-Encapsulated-Layout-Height' V:[UITableViewCellContentView:0x7f94de5773a0(91)]>"
 )

Will attempt to recover by breaking constraint 

<NSLayoutConstraint:0x7f94dced2b60 V:[UITextView:0x7f94d9b2b200'Brief text: Lorem Ipsum i...'(388)]>

388 is my calculated height, the other constraints on the UITextView are mine from Xcode/IB.

The final one is bothering me - I'm guessing that UIView-Encapsulated-Layout-Height is the calculated height of the cell when it is first rendered - (I set my UITextView height to be >= 70.0) however it doesn't seem right that this derived constraint then overrules an updated user cnstraint.

Worse, although the layout code says it's trying to break my height constraint, it doesn't - it goes on to recalculate the cell height and everything draws as I would like.

So, what is NSLayoutConstraint UIView-Encapsulated-Layout-Height (I'm guessing it is the calculated height for automatic cell sizing) and how should I go about forcing it to recalculate cleanly?

Upvotes: 311

Views: 118318

Answers (23)

Fattie
Fattie

Reputation: 12582

The simple fact is this is a long-standing undeniable bug from Apple.

It's totally illogical, but, you have to reduce the priority of your final bottom constraint in the vertical chain of constraints.

enter image description here

That's all there is to it, end of story. Apple haven't fixed this in 20? years so it's unlikely they ever will.

UIKit has a number of "totally insane" strange behaviors or plain bugs, that will never be fixed, and this is one of them.

Upvotes: 5

user3151675
user3151675

Reputation: 58019

If UIView-Encapsulated-Layout-Width and UIView-Encapsulated-Layout-Height is zero for you, you might use the wrong table view/collection view instance when returning a cell using dequeueReusableCell.

Upvotes: -1

Dhruv Saraswat
Dhruv Saraswat

Reputation: 1132

Che's answer set me on the right track. I had created an outlet of a height constraint in my UITableViewCell, and I was changing this height constraint at run-time based on some conditions.

Instead of this -

myHeightConstraint.constant = 0.0

I wrote -

myHeightConstraint.constant = CGFloat.zero

and that fixed this warning for me. Basically whatever height is returned in the heightForRowAt method should be the same as the height calculated using the constraints at runtime.

Upvotes: 0

Stefan Olarescu
Stefan Olarescu

Reputation: 1

In my case, I did manage to get rid of the warning by setting the priority of the constraint that Xcode was complaining about to 750, but the cell was still using a wrong height after deleting and reinserting it into the table.

The problem came from the fact that the calls to the beginUpdates() and endUpdates() (in between where I did my deletions and insertions) methods were encapsulated in an UIView.animate(withDuration:) animation block, where I wanted to control the duration of the animation when updating the table. Removing the call to the animation block fixed the issue for me.

Upvotes: 0

Frank
Frank

Reputation: 320

If you have UIView-Encapsulated-Layout-Height warning in debug console with Xib/Storyboard.

You should do these thing:

  1. Go Size Inspector page
  2. Check the Row Height checkbox Automatic. Record the Row Height Value
  3. Set tableView.estimatedRowHeight to that Value

🎉 NO MORE Warning⚠️

Upvotes: 1

Ortwin Gentz
Ortwin Gentz

Reputation: 54111

Try to lower the priority of your _collapsedtextHeightConstraint to 999. That way the system supplied UIView-Encapsulated-Layout-Height constraint always takes precedence.

It is based on what you return in -tableView:heightForRowAtIndexPath:. Make sure to return the right value and your own constraint and the generated one should be the same. The lower priority for your own constraint is only needed temporarily to prevent conflicts while collapse/expand animations are in flight.

Addition: While it may be debatable if the system supplied constraint is correct or not, there's no point in fighting the framework. Simply accept that the system constraint takes precedence. If you think the system constraint is wrong, make sure to return the correct rowHeight from the delegate.

Upvotes: 333

shelll
shelll

Reputation: 3373

In my case, the issue was with a vertical UIStackView inside a UITableViewCell, which was showing/hiding rows based on the data. I am using auto-sizing cells and the cell itself was always displayed correctly, with the correct height. Just the logs were full of constraints exceptions about UIView-Encapsulated-Layout-Height.

I resolved the issue by setting a lower priority to the UIStackView's top and bottom constraints (999 instead of the default 1000). Now there are no constraints exceptions, and the table looks and behaves identically.

Upvotes: 3

K_Mohit
K_Mohit

Reputation: 528

I had the same issue.For me the error was of 0.5 pixel.

2020-08-06 21:33:20.947369+0530 DemoNestedTableView[4181:384993] [LayoutConstraints] 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. 
(

        "<NSLayoutConstraint:0x600000a3abc0 UICollectionView:0x7fde0780c200.height == 326   (active)>",
        "<NSLayoutConstraint:0x600000a3ae40 V:|-(0)-[UICollectionView:0x7fde0780c200]   (active, names: '|':UITableViewCellContentView:0x7fde05e0cb10 )>",
        "<NSLayoutConstraint:0x600000a3af30 V:[UICollectionView:0x7fde0780c200]-(0)-|   (active, names: '|':UITableViewCellContentView:0x7fde05e0cb10 )>",
        "<NSLayoutConstraint:0x600000a2a4e0 'UIView-Encapsulated-Layout-Height' UITableViewCellContentView:0x7fde05e0cb10.height == 326.5   (active)>"
    )

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x600000a3abc0 UICollectionView:0x7fde0780c200.height == 326   (active)>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKitCore/UIView.h> may also be helpful.

So just added this and it worked.

self.tableView.separatorStyle = .none

Upvotes: 4

Ankur Lahiry
Ankur Lahiry

Reputation: 2315

No one answered it how to solve the case in storyboard. You have the case of mine, top bottom constraint with fixed height with priority 1000. That is why, when first time loading , as the table view cell height is 0, tries to set the element with the fixed height, causing a constraint conflict. (I am trying to insert 40 pixel in a 0 pixel height area, so compiler tries discarding the 40 pixel height). Once the tableview loaded, it will not generate (Like pop back to the tableview or switching tab bar tab)

So change the priority from required @1000 to High @750 or Low @250. For the first time loading, lower priorities will not be considered, then resizing the all constraints in layoutSubviews()

enter image description here

Upvotes: 3

UMAD
UMAD

Reputation: 637

99.9% of the time, while using custom cells or headers, all conflicts of UITableViews occur when the table loads of the first time. Once loaded you will usually not see the conflict again.

This happens because most developers typically use a fixed height or anchor constraint of some sort to layout an element in the cell/header. The conflict occurs because when the UITableView first loads/being laid out, it sets the height of its cells to 0. This obviously conflicts with your own constraints. To solve this, simply set any fixed height constraints to a lower priority (.defaultHigh). Read carefully the console message and see which constraint the layout system decided to break. Usually this is the one that needs its priority changed. You can change the priority like this:

let companyNameTopConstraint = companyNameLabel.topAnchor.constraint(equalTo: companyImageView.bottomAnchor, constant: 15)
    companyNameTopConstraint.priority = .defaultHigh

NSLayoutConstraint.activate([
            companyNameTopConstraint,
           the rest of your constraints here
            ])

Upvotes: 58

Rich
Rich

Reputation: 121

I had a similar problem with a collection view cell.

I solved it by lowering the priority of the final constraint that was linked to the bottom of the cell (the last one in the chain from the top to the bottom of the view - this is ultimately what determines its height) to 999.

The height of the cell was correct, and the warnings went away.

Upvotes: 5

Che
Che

Reputation: 1700

I had this error when using UITableViewAutomaticDimension and changing a height constraint on a view inside the cell.

I finally figured out that it was due to the constraint constant value not being rounded up to the nearest integer.

let neededHeight = width / ratio // This is a CGFloat like 133.2353
constraintPictureHeight.constant = neededHeight // Causes constraint error
constraintPictureHeight.constant = ceil(neededHeight) // All good!

Upvotes: 6

Clifton Labrum
Clifton Labrum

Reputation: 14060

I was able to resolve this error by removing a spurious cell.layoutIfNeeded() that I had in my tableView's cellForRowAt method.

Upvotes: 14

kathy zhou
kathy zhou

Reputation: 62

Set this view.translatesAutoresizingMaskIntoConstraints = NO; should resolve this issue.

Upvotes: 1

Phu Nguyen
Phu Nguyen

Reputation: 261

As mentioned by Jesse in question's comment, this works for me:

self.contentView.autoresizingMask = UIViewAutoresizingFlexibleHeight;

FYI, this issue not occurs in iOS 10.

Upvotes: 6

Golden Thumb
Golden Thumb

Reputation: 2571

I have a similar scenario: a table view with one row cell, in which there are a few lines of UILabel objects. I'm using iOS 8 and autolayout.

When I rotated I got the wrong system calculated row height (43.5 is much less than the actual height). It looks like:

"<NSLayoutConstraint:0x7bc2b2c0 'UIView-Encapsulated-Layout-Height' V:[UITableViewCellContentView:0x7bc37f30(43.5)]>"

It's not just a warning. The layout of my table view cell is terrible - all text overlapped on one text line.

It surprises me that the following line "fixes" my problem magically(autolayout complains nothing and I get what I expect on screen):

myTableView.estimatedRowHeight = 2.0; // any number but 2.0 is the smallest one that works

with or without this line:

myTableView.rowHeight = UITableViewAutomaticDimension; // by itself this line only doesn't help fix my specific problem

Upvotes: 74

After spending some hours scratching my head with this bug I finally found a solution that worked for me. my main problem was that I had multiple nibs registered for different cell types but one cell type specifically was allowed to have different sizes(not all instances of that cell are going to be the same size). so the issue arose when the tableview was trying to dequeue a cell of that type and it happened to have a different height. I solved it by setting

self.contentView.autoresizingMask = UIViewAutoresizingFlexibleHeight; self.frame = CGRectMake(0, 0, self.frame.size.width, {correct height});

whenever the cell had its data to calculate its size. I figure it can be in

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

something like

cell.contentView.autoresizingMask = UIViewAutoresizingFlexibleHeight; cell.frame = CGRectMake(0, 0, self.frame.size.width, {correct height});

Hope this helps!

Upvotes: 1

user1687195
user1687195

Reputation: 9196

I was getting a message like this:

Unable to simultaneously satisfy constraints...
...
...
...
NSLayoutConstraint:0x7fe74bdf7e50 'UIView-Encapsulated-Layout-Height' V:[UITableViewCellContentView:0x7fe75330c5c0(21.5)]
...
...
Will attempt to recover by breaking constraint NSLayoutConstraint:0x7fe0f9b200c0 UITableViewCellContentView:0x7fe0f9b1e090.bottomMargin == UILabel:0x7fe0f9b1e970.bottom

I'm using a custom UITableViewCell with UITableViewAutomaticDimension for the height. And I've also implemented the estimatedHeightForRowAtIndex: method.

The constraint that was giving me problems looked something like this

[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[title]-|" options:0 metrics:nil views:views];

Changing the constraint to this will fix the problem, but like another answer I felt that this wasn't correct, as it lowers the priority of a constraint that I want to be required:

[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-6@999-[title]-6@999-|" options:0 metrics:nil views:views];

However, what I noticed is that if I actually just remove the priority, this also works and I don't get the breaking constraint logs:

[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-6-[title]-6-|" options:0 metrics:nil views:views];

This is a bit of a mystery as to what the difference is between |-6-[title]-6-| and |-[title-|. But specifying the size isn't an issue for me and it gets rid of the logs, and I don't need to lower the priority of my required constraints.

Upvotes: 0

user2962814
user2962814

Reputation: 1

TableView get height for cell at indexPath from delegate. then get cell from cellForRowAtIndexPath:

top (10@1000)
    cell
bottom (0@1000)

if cell.contentView.height:0 //<-> (UIView-Encapsulated-Layout-Height:0@1000) top(10@1000) conflicted with (UIView-Encapsulated-Layout-Height:0@1000),

because of they priorities are is equal 1000. We need set top priority under UIView-Encapsulated-Layout-Height's priority.

Upvotes: 0

Jeff Bowen
Jeff Bowen

Reputation: 6162

I was able to get the warning to go away by specifying a priority on one of the values in the constraint the warning messages says it had to break (below "Will attempt to recover by breaking constraint"). It appears that as long as I set the priority to something greater than 49, the warning goes away.

For me this meant changing my constraint the warning said it attempted to break:

@"V:|[contentLabel]-[quoteeLabel]|"

to:

@"V:|-0@500-[contentLabel]-[quoteeLabel]|"

In fact, I can add a priority to any of the elements of that constraint and it will work. It doesn't seem to matter which one. My cells end up the proper height and the warning is not displayed. Roger, for your example, try adding @500 right after the 388 height value constraint (e.g. 388@500).

I'm not entirely sure why this works but I've done a little investigating. In the NSLayoutPriority enum, it appears that the NSLayoutPriorityFittingSizeCompression priority level is 50. The documentation for that priority level says:

When you send a fittingSize message to a view, the smallest size that is large enough for the view's contents is computed. This is the priority level with which the view wants to be as small as possible in that computation. It's quite low. It is generally not appropriate to make a constraint at exactly this priority. You want to be higher or lower.

The documentation for the referenced fittingSize message reads:

The minimum size of the view that satisfies the constraints it holds. (read-only)

AppKit sets this property to the best size available for the view, considering all of the constraints it and its subviews hold and satisfying a preference to make the view as small as possible. The size values in this property are never negative.

I haven't dug beyond that but it does seem to make sense that this has something to do with where the problem lies.

Upvotes: 35

Cullen SUN
Cullen SUN

Reputation: 3547

Another possibility:

If you using auto layout to calculate the cell height (contentView's height, most of the time as below), and if you have uitableview separator, you need to add the separator height, in order to return for the cell height. Once you get the correct height, you won't have that autolayout warning.

- (CGFloat)calculateHeightForConfiguredSizingCell:(UITableViewCell *)sizingCell {
   [sizingCell setNeedsLayout];
   [sizingCell layoutIfNeeded];
   CGSize size = [sizingCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
   return size.height; // should + 1 here if my uitableviewseparatorstyle is not none

}

Upvotes: 6

Kim
Kim

Reputation: 1452

Sizing the text view to fit its content, and updating the height constraint constant to the resulting height, fixed the UIView-Encapsulated-Layout-Height constraint conflict for me, e.g.:

[self.textView sizeToFit];
self.textViewHeightConstraint.constant = self.textView.frame.size.height;

Upvotes: 1

Austin
Austin

Reputation: 5655

Instead of informing the table view to update its constraints, try reloading the cell:

[tableView beginUpdates];

[_briefCell collapse:!_showFullBriefText];

[tableView reloadRowsAtIndexPaths:@[[tableView indexPathForCell:_briefCell]] withRowAnimation:UITableViewRowAnimationNone];

[tableView endUpdates];

UIView-Encapsulated-Layout-Height is probably the height the table view calculated for the cell during the initial load, based on the cell's constraints at that time.

Upvotes: 9

Related Questions