swiftxcodensviewcustom-viewnsscrollview

No scrollbars appear when adding a custom view via addSubview to NSScrollView


I dynamically want to add a custom NSView as a content of a NSScrollView via code in runtime. So I added a NSScrollView to my NSWindow, created an outlet to this NSScrollView and add my custom view.

@IBOutlet var myScrollView: NSView!
@IBOutlet var myCustomView: NSView!

myScrollView.addSubview(myCustomView)

This works fine (the content of myCustomView is shown in the NSScrollView) but the NSScrollView scrollbars are disabled and the content (that is larger than the NSScrollView) cannot be scrolled.

Is there something I am missing? Thanks!


Solution

  • To add scrollable content to a NSScrollView you should set documentView and not via addSubview(_:)

    let myView = MyView(frame: <somerect>)
    scrollView.documentView = myView
    

    If scrolling is still not working you may need to specify contentSize

    Docs for NSScrollView