Knowledge
Search knowledge... ⌘K
Knowledge · Guidelines · swift
Swift Appkit Layout Scrollview Stack
Standard AppKit recipe for a vertical-scrolling NSStackView inside an NSScrollView. Fixes the "history window renders empty" bug class caused by missing width-pin between the scroll view's content view and the documentView.
Metadata
swift swift recommended
Procedures
Showing 3 of 5
- 1 Create the NSScrollView with drawsBackground = false and borderType = .noBorder
```swift let scroll = NSScrollView() scroll.translatesAutoresizingMaskIntoConstraints = false scroll.hasVerticalScroller = true scroll.borderType = .noBorder scroll.drawsBackground = false ```
- 2 Create the NSStackView with .vertical orientation and .fill distribution
```swift let stack = NSStackView() stack.orientation = .vertical stack.alignment = .leading stack.distribution = .fill // CRITICAL — .fill stretches children to content width stack.spacing = 12 stack.edgeInsets = NSEdgeInsets(top: 16, left: 16, bottom: 16, right: 16) stack.translatesAutoresizingMaskIntoConstraints = false ``` `.fill` distribution stretches each arranged subview to the full perpendicular-axis width. Without it, children collapse to their intrinsic size (often 0).
- 3 Wrap the stack in a documentView and pin its width to contentView.widthAnchor
```swift let clip = NSView() clip.translatesAutoresizingMaskIntoConstraints = false clip.addSubview(stack) NSLayoutConstraint.activate([ stack.leadingAnchor.constraint(equalTo: clip.leadingAnchor), stack.trailingAnchor.constraint(equalTo: clip.trailingAnchor), stack.topAnchor.constraint(equalTo: clip.topAnchor), stack.bottomAnchor.constraint(equalTo: clip.bottomAnchor), ]) scroll.documentView = clip // CRITICAL — pin documentView width to scroll content width. // Height is left free so content drives vertical scroll. NSLayoutConstraint.activate([ clip.widthAnchor.constraint(equalTo: scroll.contentView.widthAnchor), clip.topAnchor.constraint(equalTo: scroll.contentView.topAnchor), ]) ```