视图层次结构没有为约束做好准备?
Posted
技术标签:
【中文标题】视图层次结构没有为约束做好准备?【英文标题】:The view hierarchy is not prepared for the constraint? 【发布时间】:2015-08-12 19:51:15 【问题描述】:我收到以下错误,即使我在添加按钮和应用约束之前设置了表格视图页脚。在-viewDidLoad
和-viewDidAppear
中设置和页脚视图后,我尝试调用以下方法。我似乎无法隔离问题。
视图层次结构没有为约束做好准备: 当添加到 视图,约束的项目必须是该视图的后代(或 查看自己)。如果需要解决约束,这将崩溃 在组装视图层次结构之前。打破 - [UIView _viewHierarchyUnpreparedForConstraint:] 进行调试。
2015-08-12 15:43:05.086 myApp[2293:299005] 未准备好查看层次结构 为约束。约束:容器层次结构:> | > 在容器层次结构中找不到视图: > 该视图的超级视图:;层 = ;内容偏移:0, 0;内容大小:800, 75>
这是我用来添加按钮和应用约束的代码:
- (void)addButtonContraints
//Create button
_nextQuestionButton = [UIButton buttonWithType:UIButtonTypeSystem];
[_nextQuestionButton addTarget:self action:@selector(nextQuestion) forControlEvents:UIControlEventTouchUpInside];
//_nextQuestionButton.frame = CGRectMake(0, 0, 200,40);
[_nextQuestionButton setTitle:@"Next Question" forState:UIControlStateNormal];
[_nextQuestionButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
_nextQuestionButton.backgroundColor = [UIColor whiteColor];
_nextQuestionButton.titleLabel.attributedText = [[NSAttributedString alloc] initWithString:@"Next Question"
attributes:@NSForegroundColorAttributeName:[UIColor blackColor], NSFontAttributeName:[UIFont fontWithName:@"HelveticaNeue-Bold" size:18.0f]];
//Add shadow to button
UIBezierPath *shadowPath = [UIBezierPath bezierPathWithRect:_nextQuestionButton.bounds];
_nextQuestionButton.layer.masksToBounds = NO;
_nextQuestionButton.layer.shadowColor = [UIColor blackColor].CGColor;
_nextQuestionButton.layer.shadowOffset = CGSizeMake(0.0f, 5.0f);
_nextQuestionButton.layer.shadowOpacity = 0.25f;
_nextQuestionButton.layer.shadowPath = shadowPath.CGPath;
[_nextQuestionButton setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.quizTableView.tableFooterView addSubview:_nextQuestionButton];
//Add contraints to button
NSDictionary *dict = NSDictionaryOfVariableBindings(_nextQuestionButton);
//width
[_nextQuestionButton addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[_nextQuestionButton(200)]"
options:0x00
metrics:nil
views:dict]];
//height
[_nextQuestionButton addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[_nextQuestionButton(40)]"
options:0x00
metrics:nil
views:dict]];
//right
[_nextQuestionButton addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"[_nextQuestionButton]-40-|"
options:0x00
metrics:nil
views:dict]];
//top
[_nextQuestionButton addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-20-[_nextQuestionButton]"
options:0x00
metrics:nil
views:dict]];
_nextQuestionButton.hidden = YES;
【问题讨论】:
【参考方案1】:您应该将最后两个约束添加到 self.quizTableView.tableFooterView,而不是 _nextQuestionButton。
【讨论】:
以上是关于视图层次结构没有为约束做好准备?的主要内容,如果未能解决你的问题,请参考以下文章