cocoaautolayoutappkitnssplitview

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


My question is a duplicate of this question asked 4 years ago, but it was never answered.

I have an NSSplitView with two subviews. The right subview has a label I want to center horizontally and vertically. The basic skeleton looks like this:

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

Then I added in the Auto Layout code:

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

but now the slider can't be adjusted and the window can only be resized horizontally. The right view remains fixed in size.

enter image description here

I've tried various combinations of translatesAutoresizingMaskIntoConstraints =, setContentHuggingPriority(:for:) and setHoldingPriority(:forSubviewAt:) but nothing works.

I can recreate this view in Interface Builder with no problems, but I don't know how to do it programmatically.


Solution

  • Set translatesAutoresizingMaskIntoConstraints of the subview to false.

    title.translatesAutoresizingMaskIntoConstraints = false
    

    From the documentation of 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.