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

ios constraints center view programmatically
nslayoutconstraint center in superview
cgrect center swift
center uiview in superview
autolayout programmatically center
nslayoutconstraint center multiplier
subview frame in swift
center image in swift

I have a custom UIView subclass which is being initialized via a nib.

In -awakeFromNib, I'm creating a subview and attempting to center it in its superview.

[self setInteralView: [[UIView alloc] init]];
[[self internalView] addConstraint: [NSLayoutConstraint constraintWithItem: [self internalView]
                                                                 attribute: NSLayoutAttributeCenterX
                                                                 relatedBy: NSLayoutRelationEqual
                                                                    toItem: self
                                                                 attribute: NSLayoutAttributeCenterX
                                                                multiplier: 1
                                                                  constant: 0]];

This breaks, and causes the following output:

2013-08-11 17:58:29.628 MyApp[32414:a0b] The view hierarchy is not prepared for the constraint: <NSLayoutConstraint:0xc1dcc80 UIView:0xc132a40.centerX == MyView:0xc1315a0.centerX>
    When added to a view, the constraint's items must be descendants of that view (or the view itself). This will crash if the constraint needs to be resolved before the view hierarchy is assembled. Break on -[UIView _viewHierarchyUnpreparedForConstraint:] to debug.
2013-08-11 17:58:29.630 MyApp[32414:a0b] View hierarchy unprepared for constraint.
    Constraint: <NSLayoutConstraint:0xc1dcc80 UIView:0xc132a40.centerX == MyView:0xc1315a0.centerX>
    Container hierarchy: 
<UIView: 0xc132a40; frame = (0 0; 0 0); clipsToBounds = YES; layer = <CALayer: 0xc132bc0>>
    View not found in container hierarchy: <MyView: 0xc1315a0; frame = (-128 -118; 576 804); layer = <CALayer: 0xc131710>>
    That view's superview: <UIView: 0xc131a70; frame = (0 0; 320 568); autoresize = W+H; layer = <CALayer: 0xc131b50>>

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]];

How to center a view in its container, If you're using Auto Layout, you can center your child view inside its parent like this: childView.centerXAnchor.constraint(equalTo: parentView. Don't use the HTML element <center> to center images and text; it has been deprecated, and modern web browsers no longer support it. This, in large part, is a response to HTML5's clear separation of structure and style: HTML creates structure, and CSS dictates style.

For others who come here: I got this error, because I added the constraints before I added the subviews to the hierarchy.

Programming IOS 4: Fundamentals of IPhone, IPad, and IPod Touch , Imagine a subview that is centered in its superview and is to stay centered, and is not to resize itself as the superview is resized. It would have springs externally  Centering vertically. CSS level 2 doesn't have a property for centering things vertically. There will probably be one in CSS level 3 (see below).But even in CSS2 you can center blocks vertically, by combining a few properties.

Programming IOS 5: Fundamentals of IPhone, IPad, and IPod Touch , If it is YES, then a subview will respond automatically to its superview's being For example: • Imagine a subview that is centered in its superview and is to stay  You can center text with CSS by specifying the text-align property of the element to be centered. Centering a few blocks of text If you only have one or a few blocks of text to center, add the style attribute to the element's opening tag and use the "text-align" property. In the example below, we've added them to the <p> tag.

Additional Tips:

I have a newly developed App which running fine on iOS7 but get error on iOS8 "The view hierarchy is not prepared for the constraint".

Read some other post said that the (sub)views need to be added before create constraints. I did that but still got the error.

Then I figured out that I should create constraints under -(void)viewDidAppear instead of viewDidLoad

Programming IOS 8: Dive Deep Into Views, View Controllers, and , A subview will respond to its superview's being resized, in accordance with the For example: • Imagine a subview that is centered in its superview and is to  Centering simply means subtracting a constant from every value of a variable. What it does is redefine the 0 point for that predictor to be whatever value you subtracted. It shifts the scale over, but retains the units. The effect is that the slope between that predictor and the response variable doesn’t change at all.

This is an old question but I want to point out this line from the docs:

When developing for iOS 8.0 or later, set the constraint’s isActive property to true instead of calling the addConstraint(_:) method directly. The isActive property automatically adds and removes the constraint from the correct view.

At the very least, this will remove one point of failure since you no longer need to worry about calling addConstraint on the wrong view

UIView extension to quickly add and fit or center a subview inside a , UIView extension to quickly add and fit or center a subview inside a superview, using constraints. MyView.swift. class MyView : UIView {. Centerview Partners is committed to the success of the companies it works with, and believes this commitment provides meaningful rewards to the people of Centerview. By creating opportunities to advance rapidly while always preserving our reputation in the marketplace and in our community, Centerview Partners is quickly establishing itself

Frame vs Bounds in iOS - Suragch, Any subviews that this view has are laid out in relation to this point. It is like Like frame , center uses the coordinate system of the parent view. Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, PHP, Python, Bootstrap, Java and XML.

UIStackView: Distribution vs. Alignment, For equalCentering , the subviews are placed so that center-to-center spacing between views is the same. For equalSpacing , the spacings  Centering the page in center of your monitor How do I center a page in the center of my monitor? I go to view > 1 page, but if I do that, although the page is centered, as soon as I zoom in, the entire page is set off to the left, as if it were in a 2 page view.

UIStackView, The stack uses 8.0 point spacing and the center alignment. The stack When a subview is removed from the stack view, the stack view also removes it from the  Hayes (2013) offers a good discussion of mean centering, pp. 282-290. As he states mean centering is not necessary, and it actually does nothing to reduce multicollinearity between predictor X and

Comments
  • That gives me an error claiming Unable to simultaneously satisfy constraints. Probably at least one of the constraints in the following list is one you don't want. And then it breaks <NSLayoutConstraint:0x126ad4c0 UIView:0xadd2e20.centerX == MyView:0xadd19b0.centerX>
  • Most likely because you didn't disable translation of auto resizing mask into constraints. I'll update my code above to do so. You'll probably also need to add width/height constraints for it to be visible, and I would recommend adding a constraint on center Y or some sort of top/bottom constraint to self to make the layout well defined.
  • so you cant have layout like: @"V:|[v]|" ? as this would refer to a superview?
  • @Sam That's a valid constraint, but it won't center the view represented by [v], it will give you top and bottom constraints of the standard size between [v]'s top and bottom edges and that of its superview. You would also have to add it to the superview, I believe.
  • A simple thumb rule : Any constraints that relates to the size of a view should be added to the same view and any constraints that relates to its position should be added to its parent.
  • Thanks, you saved me a lot of time!
  • This is the most common reason for this failure I have noticed so far.
  • exactly and when you do that constraintWithItem: youView the item is not exist in it!
  • When viewDidAppear() is called, the view is already visible to the user. If modifying constraints it should be before that, in viewWillLayoutSubviews(). More of the lifecycle here: medium.com/@SergiGracia/…