Search code examples
cocoaoverlaynsviewnsscrollview

Overlay NSView over NSScrollView


I have an NSScrollView that fills an entire window and displays a huge image. Now I would like to overlay a custom NSView over parts of the Scroll View (eg. top 20 Pixels height and window width) to display additional information. As the user scrolls the scroll view, the custom NSView at the top should stay where it is.

I have tried the following:

  1. Create an instance of NSView of the size of my window
  2. Add NSScrollView as subview of the previously generated NSView
  3. Add my custom view as subview to the NSView in step 1

This works in the beginning, the scroll view is displayed properly and my custom NSView as well. However, as soon as I start moving the scroll view (scrolling) the custom NSView is scrolled along with the content of the NSScrollView and eventually disappears when its moved outside of the bounds and the part of scroll view, where it was positioned, becomes redrawn. How could I effectively layer my custom NSView on top of the NSScrollView and make sure it stays put?

Thanks!


Solution

  • I know that you already have a working solution for this, but I happened to be looking for the same thing myself recently and I came across the LKOverlayWindow class by Louis Klaassen, which seems to provide an easy solution for this kind of overlay.

    As described on the CocoaDev wiki, you just need to create a new NSWindow in Interface Builder, have it be an instance of LKOverlayWindow, and either attach the NSScrollView through an outlet or specify it in code. Once attached to a scroll view, the contents of the LKOverlayWindow will overlay the scroll view and track it as it moves and is resized (the latter only seems to work with the NSScrollView as an outlet of the window). A sample project is provided by the author here.

    I was going to go the way of subclassing NSScrollView, but this turned out to be much easier in my case.