我的问题与 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
然后我添加了自动布局代码:
customView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
title.centerXAnchor.constraint(equalTo: customView.centerXAnchor),
title.centerYAnchor.constraint(equalTo: customView.centerYAnchor),
])
但现在 slider 无法调整,窗口只能水平调整大小。右 View 的大小保持固定。
我尝试了 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/