cocoa - 如何在 NSSplitView 的 subview 中使用自动布局?

标签 cocoa autolayout appkit nssplitview

我的问题与 this question asked 4 years ago 重复,但从未得到答复。

我有一个带有两个 subview 的 NSSplitView。右侧 subview 有一个我想要水平和垂直居中的标签。基本框架如下所示:

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

enter image description here

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

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

但现在 slider 无法调整,窗口只能水平调整大小。右 View 的大小保持固定。

enter image description here

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

我可以在 Interface Builder 中重新创建此 View ,没有任何问题,但我不知道如何以编程方式执行此操作。

最佳答案

将 subview 的 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.

关于cocoa - 如何在 NSSplitView 的 subview 中使用自动布局?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57137252/

相关文章:

iphone - AutoLayout 为多个 View 设置相同的高度和顶部空间,而不是垂直分布

ios - 以编程方式将视网膜照片分配给 UIButton

ios - Autolayout - 2 个具有动态长度的标签

SwiftUI:NSViewControllerRepresentable 中的 NSPageController 崩溃

cocoa - 如何清除 NSTextView 选择而不使其成为第一响应者?

swift - NSView 未被释放

cocoa - 使用 NSWindowController 加载 NIB 文件不会设置窗口或顶级对象

cocoa - 在 cocoa 中观察 self

macos - 显示 NSWindow 下面的内容的最佳方式是什么?

cocoa - 如何从 NSTextField 的字段编辑器中拦截击键?