iOS,添加程序化约束

时间:2015-11-13 20:52:01

标签: ios objective-c constraints

我正在阅读iOS教科书16章中的Big Nerd Ranch并尝试以编程方式添加约束(Xcode 7.1,iOS),但会导致以下错误:

The view hierarchy is not prepared for the constraint: <NSLayoutConstraint:0x7f96f1e272a0 H:|-(0)-[UIImageView:0x7f96f1e3ba90]   
(Names: '|':UIControl:0x7f96f1e33550 )>
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(UIConstraintBasedLayout) _viewHierarchyUnpreparedForConstraint:] to debug.`

BNRDetailViewController.xib文件是BNRDetailViewController的视图。以下是我尝试在BNRDetailViewController中使用的代码:

- (void)viewDidLoad
{
[super viewDidLoad];

UIImageView *iv = [[UIImageView alloc] initWithImage:nil];

// The contentMode of the image view in the XIB was aspect fit
iv.contentMode = UIViewContentModeScaleAspectFit;

// Do not produce a translated constraint for this view
iv.translatesAutoresizingMaskIntoConstraints = NO;

// The image view was a subview of the view
[self.view addSubview:iv];

// The image view was pointed to by the imageView property
self.imageView = iv;

NSDictionary *nameMap = @{@"imageView": self.imageView,
                          @"dateLabel": self.dateLabel,
                          @"toolbar": self.toolbar};

// imageView is 0 pts from superview at left and right edges
NSArray *horizontalConstraints =
[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[imageView]-0-|" options:0 metrics:nil views:nameMap];

// imageView is 8 pts from dateLabel at its top edge
// and 8 pts from toolbar at its bottom edge
NSArray *verticalConstraints =
[NSLayoutConstraint constraintsWithVisualFormat:@"V:[dateLabel]-[imageView]-[toolbar]" options:0 metrics:nil views:nameMap];

[self.view addConstraints:horizontalConstraints];
[self.view addConstraints:verticalConstraints];
}

2 个答案:

答案 0 :(得分:0)

您编写的用于创建和应用约束的代码似乎很好(当我在我自己的项目中尝试它时它起作用)。所以你的问题必须在其他地方。尝试在调试器中运行,并将错误消息中给出的地址与self.imageView和self.view的地址进行比较。也许其中一个没有正确设置。

特别是,错误说&#34; |&#34; (superview正在映射到uiControl。这不一定是个问题,但看起来有点可疑。我通常希望你将一个子视图添加到UIView,而不是一个控件

答案 1 :(得分:0)

好的,我发现问题也回答了我的另一个未回答的问题(https://stackoverflow.com/questions/33662924/ios-change-size-of-xib-view-to-wany-hany-xcode-7-1)。在File Inspector, Interface Builder Document我选择了两个选项:Use Auto LayoutUse Size Classes。默认情况下,当我们在Xcode 7中创建新的.xib时,会选择两个选项。取消选中Use Size Classes解决当前问题的问题,该程序不再崩溃。它还解决了另一个问题,让我在不同的模拟器上成功运行应用程序而不会消失视图。

虽然问题已经解决,但我遇到了另一个问题:Developing universal in Xcode 6 所以,如果,比方说,我想要一个通用的应用程序,并指定iPhone与iPad的不同设置,我仍然不知道如何做到这一点。如果您按照他们在链接问题中提出的建议(他们选择两个选项),您可能会像我一样遇到Xcode 7的问题。也许我能想到的唯一解决方案是尝试覆盖UIViewControllers和其他方法的supportedInterfaceOrientations方法,以根据设备更改行为。但是,iOS9之前的许多可用于控制方向的方法(例如,statusBarOrientation)已被弃用,Apple现在建议使用Use Size Classes选项...