高度限制,lessThanOrEqualToConstant,但尽可能尝试达到常量

Height constraint, lessThanOrEqualToConstant, but tries to achieve the constant if possible

我有两个视图,previewSection 和 settingsEditSection。我正在尝试对这些视图进行布局以实现以下目标:

我的问题是,当我给 previewSection 设置高度 lessThanOrEqualToConstant: 400 时,它的实际高度为 0。

有什么方法可以让我说:"height of lessThanOrEqualToConstant, x, and as long as theres room, have the height of x"?

我希望 settingsEditSection 的高度 150 是第一优先级,然后在让它变大之前,如果可能的话,将 previewSection 设为 400,如果之后还有空间,那么 settingsEditSection 可以大于 150 来填充在 space.

这是我编写的代码,对我来说最有意义:

let previewSection = PreviewSection()
view.addSubview(previewSection)
let settingsEditSection = SettingsEditSection()
view.addSubview(settingsEditSection)
// Preview section
previewSection.translatesAutoresizingMaskIntoConstraints = false
previewSection.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
previewSection.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
previewSection.topAnchor.constraint(equalTo: view.topAnchor, constant: topMargin).isActive = true
previewSection.heightAnchor.constraint(lessThanOrEqualToConstant: 400).isActive = true
previewSection.bottomAnchor.constraint(equalTo: settingsEditSection.topAnchor).isActive = true
// Settings & edit section
settingsEditSection.translatesAutoresizingMaskIntoConstraints = false
settingsEditSection.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
settingsEditSection.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
settingsEditSection.bottomAnchor.constraint(equalTo: upgradeButton.topAnchor).isActive = true
settingsEditSection.heightAnchor.constraint(greaterThanOrEqualToConstant: 150).isActive = true
settingsEditSection.topAnchor.constraint(equalTo: previewSection.bottomAnchor).isActive = true

此时,previewSection 的高度为 0,然后 settingsEditSection 的高度刚好横跨整个父视图。

对我来说这个问题的背景是我正在构建 this profile page,并布局配置文件和按钮以在 iPhone X 和 iPhone 上看起来最好5S,这才是最好的做法

您可以在此处使用约束优先级。之后

previewSection.heightAnchor.constraint(lessThanOrEqualToConstant: 400).isActive = true

您可以再添加一个提供默认高度但优先级较低的约束。像这样,

let previewSectionHeight = previewSection.heightAnchor.constraint(equalToConstant: 400)
previewSectionHeight.priority = .defaultHigh
previewSectionHeight.isActive = true

这将使 previewSection 的高度为 400,除非 settingsEditSection 将其向上推以使其变小。为了使所有这些都起作用,您还需要为 previewSection 和 settingsEditSection 的容器视图提供一个恒定的高度。