5

I have a simple custom borderless NSWindow subclass which has a rounded rectangle shape.

In the content view of this window, I've added an NSScrollView.

How do I get the NSScrollView to clip its document view to the rounded rectangle shape of the NSWindow?

I've tried subclassing the NSScrollView, overriding drawRect: and adding a clipping path before calling super. I've also tried subclassing the document view and the clip view with the same technique but I cannot get it to clip.

BTW, this is on Lion with the elastic scrolling behaviour.

firstresponder
  • 5,000
  • 8
  • 32
  • 38

3 Answers3

4

After much fiddling, I just discovered that NSScrollView's can be made to have rounded corners by simply giving it a backing layer and setting that layer's corner radius provided you also do the same to it's internal NSClipView. Both are required, which now makes sense, since it's the clip view that actually provides the viewable window into the NSScrollView's document view.

NSScrollView * scrollView = ...;

// Give the NSScrollView a backing layer and set it's corner radius.
[scrollView setWantsLayer:YES];
[scrollView.layer setCornerRadius:10.0f];

// Give the NSScrollView's internal clip view a backing layer and set it's corner radius.
[scrollView.contentView setWantsLayer:YES];
[scrollView.contentView.layer setCornerRadius:10.0f];
Dalmazio
  • 1,835
  • 2
  • 23
  • 40
  • 2
    Note however, that this doesn't seem to work for NSScrollView's that contain NSTextView's. In this case, we need to revert back to the masking layer approach. – Dalmazio Apr 03 '12 at 09:15
  • See also: http://stackoverflow.com/questions/5268467/how-can-i-get-nsscrollview-to-respect-a-clipping-path/9989911#9989911 – Dalmazio Apr 03 '12 at 10:12
0

Even better IMO:

scrollView.wantsLayer = true
scrollView.layer?.masksToBounds = true
scrollView.contentView.wantsLayer = true
scrollView.contentView.layer?.masksToBounds = true
Christian Kienle
  • 733
  • 1
  • 14
  • 26
  • Have you actually tried this. Unfortunatelly this solution doesn't work for me... – andrii May 09 '19 at 14:05
  • Eh. Yes? Have you actually considered that this answer is over 2 years old and that it might have worked "back then"? :) – Christian Kienle May 12 '19 at 16:08
  • Please don't get me wrong :) Sorry, I have decided to check, as there was no comments to this answer. Thank you for finding time to answer. – andrii May 12 '19 at 21:41
0

In Swift I have solved like this:

scrollView.wantsLayer = true
scrollView.contentView.wantsLayer = true
scrollView.layer?.cornerRadius = 20.0
scrollView.contentView.layer?.cornerRadius = 20.0
madx
  • 6,723
  • 4
  • 55
  • 59