gpt4 book ai didi

iphone - tableHeaderView 的自动布局

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:41:48 25 4
gpt4 key购买 nike

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

事情是这样的:有一个 View Controller ,其中包含一个 UITableView 和一个 UIView。此 View 位于表格 View 的正下方,其高度未延伸到全屏高度(假设它占据了屏幕的上半部分)。

表格 View 使用分组样式并放置在上述 View 的正上方,具有半透明背景,因此您实际上可以看到其下方 View 的内容。但是,由于 View 占据了屏幕的一半,我需要向该 TableView 添加一个 tableHeaderView(也是半透明的),以便在首次加载 View Controller 时整个背景内容清晰可见。

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

这是使用 springs 和 struts 以一种简单的方式完成的,但是每次我尝试将标题添加到 TableView 时,自动布局都会使应用程序崩溃(无论我如何操作)。

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

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

(据我所知,约束不能直接添加到 TableView ,因为 otherView 不是它的 subview )

还有:

[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 高度实际绑定(bind)到 View 上的另一个元素?

我还应该指出,我已经离开 IB 很久了,所以这一切都是纯代码完成的,特别是在 loadView 上。

最佳答案

如果你为 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];

P.S:请记住 addConstraints:addConstraint: 不同。

addConstraints 与约束数组或[NSLayoutConstraints constraintsWithVisualFormat:...]

结合使用

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

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

关于iphone - tableHeaderView 的自动布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18281691/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com