如何在 NSSplitView 的子视图中使用自动布局?

How can I use Auto Layout in a subview of an NSSplitView?

我的问题与 this question asked 4 years ago 重复,但从未有人回答。

我有一个带有两个子视图的 NSSplitView。右边的子视图有一个标签,我想水平和垂直居中。基本骨架如下所示:

let window = /* ... */

let blankView = NSView(frame: .zero)
let customView = NSView(frame: .zero)
// set background colors

let title = NSTextField(labelWithString: "Title")
customView.addSubview(title)

let splitView = NSSplitView(frame: .zero)
splitView.isVertical = true
splitView.addSubview(blankView)
splitView.addSubview(customView)

window.contentView = splitView

然后我在自动布局代码中添加:

customView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
    title.centerXAnchor.constraint(equalTo: customView.centerXAnchor),
    title.centerYAnchor.constraint(equalTo: customView.centerYAnchor),
])

但现在无法调整滑块,window 只能水平调整大小。右视图保持固定大小。

我尝试了 translatesAutoresizingMaskIntoConstraints =setContentHuggingPriority(:for:)setHoldingPriority(:forSubviewAt:) 的各种组合,但没有任何效果。

我可以在 Interface Builder 中毫无问题地重新创建此视图,但我不知道如何以编程方式进行。

将子视图的 translatesAutoresizingMaskIntoConstraints 设置为 false

title.translatesAutoresizingMaskIntoConstraints = false

来自 translatesAutoresizingMaskIntoConstraints 的文档:

When this property is set to true, the view’s superview looks at the view’s autoresizing mask, produces constraints that implement it, and adds those constraints to itself (the superview). If your view has flexible constraints that require dynamic adjustment, set this property to false and apply the constraints yourself.