3

我一直在尝试通过学习自动布局来改进我的布局技术,但我偶然发现了一个我无法解决的问题。

这是发生的事情:有一个视图控制器,其中包含 aUITableView和 a UIView。这个视图被放置在表格视图的正下方,并且它的高度没有延伸到全屏高度(假设它占据了它的上半部分)。

使用分组样式并放置在上述视图上方的表格视图具有半透明背景,因此您实际上可以看到其下方视图的内容。但是,由于视图占据了屏幕的一半,我需要在这个表视图中添加一个 tableHeaderView(也是半透明的),以便在第一次加载视图控制器时可以清楚地看到整个背景内容。

这样做的最终效果就像一个固定的 tableHeaderView,当向上滚动表格视图时,它会在背景上消失。

这是使用弹簧和支柱以简单的方式完成的,但是每次我尝试将标题添加到表格视图时,自动布局都会使应用程序崩溃(无论我如何做)。

由于我正在寻找一种始终将背景中的视图高度(otherView)与 tableHeaderView 高度匹配的方法,因此我正在使用:

[self.view addConstraint:[NSLayoutConstraints constraintWithItem:headerView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:otherView attribute:NSLayoutAttributeHeight multiplier: 1 constant:0]];

(据我了解,约束不能直接添加到表视图中,因为 otherView 不是它的子视图)

并且:

[headerView setTranslatesAutoResizingMaskIntoConstraints:NO]

这些调用总是导致此崩溃:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Auto Layout still required after executing -layoutSubviews. UITableView's implementation of -layoutSubviews needs to call super.'

那么有没有办法做到这一点?是否可以使用自动布局将 tableHeaderView 高度实际绑定到视图上的另一个元素?

我还应该注意,我早就离开了 IB,所以这一切都是纯粹用代码完成的,特别是在loadView.

4

1 回答 1

0

如果您为 NSLayoutConstraint 创建一个实例变量并将其设置为:

headerViewHeightConstraint = [NSLayoutConstraint constraintWithItem:headerView
                                                          attribute:NSLayoutAttributeHeight
                                                          relatedBy:NSLayoutRelationEqual
                                                             toItem:nil
                                                          attribute:NSLayoutAttributeNotAnAttribute
                                                         multiplier:1.0f
                                                           constant:otherView.frame.size.height];

您可以通过以下方式调整其大小:

headerViewHeightConstraint.constant = 1000.0f;
[headerView updateConstraintsIfNeeded];

PS:请记住,addConstraints:这与addConstraint:.

addConstraints与一组约束结合使用或[NSLayoutConstraints constraintsWithVisualFormat:...]

addConstraint:与上面示例中的单个约束结合使用。

如果你在它的第一行覆盖layoutSubviews:调用。[super layoutSubviews]这会强制视图及其子视图自行布局,以便您可以访问它们的框架详细信息等。

于 2013-08-18T12:41:03.717 回答