我有一个以编程方式创建UILabel的子类UIView,但是当UIView被赋予约束时它不会很好...
我想做什么:
标签应位于视图顶部。
我的子类UIView将创建一个像这样的UILabel:
//In interface
@property(nonatomic, strong) UILabel *myLabel;
//in implementation
self.myLabel = [[UILabel alloc] initWithFrame:[self bounds]];
/*
set properties
*/
[self.superview addSubview:[self myLabel]];
这提供了所需的行为,标签具有与子类UIView相同的大小和位置。但是当我在故事板中为UIView添加约束时,UILabel会呈现在错误的位置。
以下是发生的事情:( UIView阴影黄色,UILabel阴影蓝绿色)
我尝试过更改
[self.superview addSubview:[self myLabel]];
到
[self addSubview:[self myLabel]];
但这也不起作用。
如何在UIView顶部进行UILabel渲染?
答案 0 :(得分:0)
如果在代码中添加标签,则还应在代码中添加约束。 约束的技巧是记住将约束添加到由约束链接的2个视图的(层次结构)最顶层视图,或者添加到第一个公共父视图。
请注意,混合IB自动布局和编码约束可能非常令人头疼。我遇到了一些情况,我必须将UIView.translatesAutoResizingMasksIntoConstraints设置为NO才能正常工作。
答案 1 :(得分:0)
我在将UILabel添加到UIView之后尝试了这个:
NSLayoutConstraint *xPosConstraint = [NSLayoutConstraint constraintWithItem:self
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:self.myLabel
attribute:NSLayoutAttributeCenterX
multiplier:1.0
constant:0];
[self addConstraint:xPosConstraint];
导致崩溃...
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>>
和
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>>'
另外,将约束添加到superview中,如下所示:
[self.superview addConstraint:xPosConstraint];
...导致调试器破坏约束,因为它不能满足。
开始讨厌自动布局...
**** ****编辑 固定它。嘎。只需要添加这个:
[self.myLabel setTranslatesAutoresizingMaskIntoConstraints:NO];