Centering Subview's X in Autolayout Throws "Not Prepared for the Constraint"

Centering subview's X in autolayout throws not prepared for the constraint

As the error states, you must add the constraint to a view such that the views involved in the constraint are the view you're adding it to or a subview of that view. In the case of your code above, you should be adding that constraint to self, rather than [self internalView]. The reason it doesn't work as written is one of the views involved in the constraint (self) is not in the view hierarchy if you consider only [self internalView] and below).

For more details, see the discussion section of the documentation on the addConstraint: method.

Here is your line of code, fixed as I suggest:

UIView* internalView = [[UIView alloc] initWithFrame:CGRectZero];
internalView.translatesAutoresizingMaskIntoConstraints = NO;
[self setInternalView:internalView];

[self addConstraint: [NSLayoutConstraint constraintWithItem: [self internalMapView]
attribute: NSLayoutAttributeCenterX
relatedBy: NSLayoutRelationEqual
toItem: self
attribute: NSLayoutAttributeCenterX
multiplier: 1
constant: 0]];

View Hierarchy Not Prepared for Constraints Even After Adding Subviews

See the error message:

When added to a view, the constraint's items must be descendants of that view (or the view itself)

In your case, all constraints should be added to self:

self.addConstraint( ...

get warning for autolayout, NSAutoLayout,objective C

You need to add the views before adding constraints.

put this first and then add constraints

self.logInButton addSubView:spinner

AutoLayout: removeFromSuperview / removeConstraints throws exception and crashes hard

I had an (extensive) conversation with an Apple engineer about this crash.

Here are the two most probable causes:

  1. You have an invalid constraint, such as view1.left = view2.left + 20 where view2 is unexpectedly nil, or has a multiplier of 0. Be sure to double (and triple) check your constraints to make sure that they are correct. Here are 2 examples of problematic constraints:

    // The first constraint would be a problem if view2 were nil
    [NSLayoutConstraint constraintWithItem:view1 attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:view2 attribute:NSLayoutAttributeBottom multiplier:1 constant:20];
    // The second constraint is a problem because the 0 multiplier causes view2 to be "lost"
    [NSLayoutConstraint constraintWithItem:view1 attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:view2 attribute:NSLayoutAttributeBottom multiplier:0 constant:5];
  2. You're hitting a bug in the internal Foundation auto layout engine related to accumulated loss of floating point precision. When you've crashed, the way you can know that this is the case is to search through the (large) exception log in the console for a very small (nearly zero) floating point number such as this:

<505:-7.45058e-08>*PWPlotLegendEntryView:0x600000582be0.Height{id: 34609} +

(Search for e- in the console output to find small numbers like this.) This number (-7.45058e-08 in this case) represents the coefficient at this particular point in time while the internal engine is solving constraints. In this case, the number is supposed to be exactly 0, but due to the way the auto layout engine does calculations with floating point numbers it has become an extremely tiny negative number instead which blows everything up. If you can find such a number in the output, you know that you've hit this bug.

How can you work around this issue?

Changing the order that you add (activate) constraints can end up changing the order of calculations in the internal engine, which as a result can cause this issue to disappear as the math is done without any problematic loss of precision.

This issue seems to come up more frequently when you have changed the content compression resistance or content hugging priorities for views, so try commenting out any code that does that to see if it's causing this bug to happen, or re-ordering it to happen earlier or later in your constraint setup code.

More details about my specific case:

I ran into this crash on iOS. The steps to reproduce it were quite interesting:

  1. A view controller containing a table view was pushed on screen (in a navigation controller).
  2. The table view had to contain enough cells so they didn't all fit in the visible area, then it had to be scrolled to the last cell and then back up a bit (presumably, this was causing cells to be reused, which was triggering this issue).
  3. Then, when the view controller containing the table view was popped off the navigation stack, immediately after the pop animation completed the app would crash at the point where the view controller's view was removed from the view hierarchy.

After a lot of trial and error I was able to isolate the issue to one specific thing: setting the content compression resistance & hugging priorities for a UIImageView in each of the table view cells. In this case, the image view is being positioned using Auto Layout inside the cell, and to achieve the correct layout the image view needs to be exactly its intrinsic content size (the size of its image).

This was the problematic code:

// Inside of the UITableViewCell's updateConstraints method...

[self.imageView setContentCompressionResistancePriority:​UILayoutPriorityRequired forAxis:​UILayoutConstraintAxisHorizontal];
[self.imageView setContentCompressionResistancePriority:​UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical];
[self.imageView setContentHuggingPriority:​UILayoutPriorityRequired forAxis:​UILayoutConstraintAxisHorizontal];
[self.imageView setContentHuggingPriority:​UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical];

Removing the above code and replacing it with 2 constraints (at Required priority) to fix the width & height of the image view to the image's size achieved the same result, but avoided the crash. Here's the replacement code (using PureLayout):

[self.imageView autoSetDimensionsToSize:self.imageView.image.size];

I also found that just moving the problematic 4 lines to a different place in my constraint setup code resolved the issue, presumably because this changed the order of calculations sufficiently to prevent the problematic loss of precision.

Application crashes when adding a Y constraint

Replace this

[labe2 addConstraint:yConstraint];

With

[self.view addConstraint:yConstraint];

Need assistance regarding creating auto layout constraints programmatically

Add constraints to self.view. Replace the following:

[view1 addConstraints:constraints];
[view1 addConstraints:verticalConstraints];

with

[self.view addConstraints:constraints];
[self.view addConstraints:verticalConstraints];

Custom UIView above UITableView (when user pulls to refresh)

The answer is: use AutoLayout.

Storyboard

You can add all the constraints you need from the storyboard

XIB

If loading a UIView programmatically, you can also add NSLayoutConstraint programmatically. They are guaranteed to work in landscape mode.

...but I can't get them working...

Look at https://stackoverflow.com/a/18759148/218152 and add constraints for refreshBackgroundView height. To pin it:

// Add constraints to fit to superview, below the nav bar
UIView * hintView = self.refreshBackgroundView;
[hintView setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.tableView addConstraints:[NSLayoutConstraint
constraintsWithVisualFormat:@"H:|-0-[hintView]-0-|"
options:NSLayoutFormatDirectionLeadingToTrailing
metrics:nil
views:NSDictionaryOfVariableBindings(hintView)]];

id<UILayoutSupport> guide = self.topLayoutGuide;
[self.tableView addConstraints:[NSLayoutConstraint
constraintsWithVisualFormat:@"V:|[guide]-0-[hintView]-0-|"
options:NSLayoutFormatDirectionLeadingToTrailing
metrics:nil
views:NSDictionaryOfVariableBindings(hintView, guide)]];

UIRefreshControl

You should really use a UIRefreshControl for long term compatibility.



Related Topics



Leave a reply



Submit