为添加到UIWindow的视图添加约束时,为什么无法设置自动布局约束?

Dou*_*ith 1 objective-c uiimageview ios autolayout nslayoutconstraint

要在屏幕上创建黑色叠加层,我将所有其他视图的视图添加到UIWindow:

UIView *darkOverlayView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
darkOverlayView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.85];
Run Code Online (Sandbox Code Playgroud)

然后我想将UIImageView置于新的中心darkOverlayView,并尝试如下:

UIImageView *imageFromLink = [[UIImageView alloc] initWithImage:responseObject];
imageFromLink.translatesAutoresizingMaskIntoConstraints = NO;
            CGFloat widerThanHeightBy = imageFromLink.bounds.size.width / imageFromLink.bounds.size.height;

[darkOverlayView addConstraint:[NSLayoutConstraint constraintWithItem:imageFromLink attribute:NSLayoutAttributeWidth relatedBy:0 toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:[UIScreen mainScreen].bounds.size.width]];
[darkOverlayView addConstraint:[NSLayoutConstraint constraintWithItem:imageFromLink attribute:NSLayoutAttributeHeight relatedBy:0 toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:[UIScreen mainScreen].bounds.size.height / widerThanHeightBy]];
Run Code Online (Sandbox Code Playgroud)

但每次运行时,我都会收到错误:

视图层次结构不是为约束准备的:当添加到视图时,约束的项必须是该视图(或视图本身)的后代.如果在组装视图层次结构之前需要解析约束,则会崩溃.打破 - [UIView _viewHierarchyUnpreparedForConstraint:]进行调试.2013-12-07 00:59:03.626 Jupiter [58008:70b]查看层次结构未准备好约束.约束:容器层次结构:>在容器层次结构中找不到视图:> - (null)该视图的超级视图:无SUPERVIEW

我怎么能绕过这个?或者我必须使用框架?

Bim*_*awa 6

怎么说@rdelmar:

第一:你在imageFromLink addview上添加你喜欢的addSubView吗?

第二:你的约束:

[darkOverlayView addConstraint:[NSLayoutConstraint constraintWithItem:imageFromLink attribute:NSLayoutAttributeWidth relatedBy:0 toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:[UIScreen mainScreen].bounds.size.width]];
[darkOverlayView addConstraint:[NSLayoutConstraint constraintWithItem:imageFromLink attribute:NSLayoutAttributeHeight relatedBy:0 toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:[UIScreen mainScreen].bounds.size.height / widerThanHeightBy]];
Run Code Online (Sandbox Code Playgroud)

设置只有Widthheight,何谈xy

只需添加两个约束:

[darkOverlayView addConstraint:[NSLayoutConstraint constraintWithItem:imageFromLink attribute:NSLayoutAttributeCenterX relatedBy:0 toItem:darkOverlayView attribute:NSLayoutAttributeCenterX multiplier:1.0f constant:0.0f]];
[darkOverlayView addConstraint:[NSLayoutConstraint constraintWithItem:imageFromLink attribute:NSLayoutAttributeCenterY relatedBy:0 toItem:darkOverlayView attribute:NSLayoutAttributeCenterY multiplier:1.0f constant:0.0f]];
Run Code Online (Sandbox Code Playgroud)

它位于darkOverlayView中心的位置.