I just tried this after adding the UILabel to the UIView:
NSLayoutConstraint *xPosConstraint = [NSLayoutConstraint constraintWithItem:self
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:self.myLabel
attribute:NSLayoutAttributeCenterX
multiplier:1.0
constant:0];
[self addConstraint:xPosConstraint];
Which caused a crash...
The view hierarchy is not prepared for the constraint:
<NSLayoutConstraint:0x7fe0f0f750d0 MyUIView:0x7fe0f0f55b90.centerX == UILabel:0x7fe0f0f71810.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.
2014-12-24 13:26:40.319 circle[28901:2153934] View hierarchy unprepared for constraint.
Constraint: <NSLayoutConstraint:0x7fe0f0f750d0 MyUIView:0x7fe0f0f55b90.centerX == UILabel:0x7fe0f0f71810'0%'.centerX>
Container hierarchy: < MyUIView: 0x7fe0f0f55b90;
frame = (200 28; 200 200); autoresize = RM+BM;
layer = <CALayer: 0x7fe0f0f54000>>
View not found in container hierarchy: <UILabel: 0x7fe0f0f71810;
frame = (200 28; 200 200); text = '0%'; userInteractionEnabled = NO;
layer = <_UILabelLayer: 0x7fe0f0f71970>>
That view's superview: <UIView: 0x7fe0f0f56760; frame = (0 0; 375 667);
autoresize = W+H; layer = <CALayer: 0x7fe0f0f56a30>>
and
2014-12-24 13:26:40.334 circle[28901:2153934] *** Terminating app due to uncaught exception
'NSGenericException', reason:
'Unable to install constraint on view.
Does the constraint reference something from outside the subtree of the view?
That's illegal.
constraint:<NSLayoutConstraint:0x7fe0f0f750d0
MyUIView:0x7fe0f0f55b90.centerX == UILabel:0x7fe0f0f71810'0%'.centerX>
view:< MyUIView: 0x7fe0f0f55b90;
frame = (200 28; 200 200); autoresize = RM+BM; layer = <CALayer: 0x7fe0f0f54000>>'
Also, adding the constraint to the superview like this:
[self.superview addConstraint:xPosConstraint];
...causes the debugger to break the constraint because it can't be satisfied.
Beginning to hate auto layout...
****Edit****
Fixed it. Gah. Just needed to add this:
[self.myLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
initmethod or an override oflayoutSubviews? It should be in the latter. - Andrew Monshizadeh