问题
I'm subclassing NSScroller to try to make it look similar to how "scrollbars" look on iOS. I want it to just be an overlay representing the current position that is drawn OVER what is under it. For whatever reason if I override drawRect for the scroller, I get the bounds filled with white. Is there any way to prevent this so that way I can just be drawing on top of what my NSScroller sub class is over?
Edit: Drawing with clear color seems to bring me close, but it is drawing "too clear" :P It's drawing right to the desktop, when I just want to be drawing down to the window. This picture might make it more clear
Any ideas?
回答1:
NSView subclasses do all their drawing starting at drawRect. If you override that method in a subclass, you're responsible for doing all of the drawing (whether through you're own methods or calling upon super's methods.) For example, the following code draws just the scroll nob and makes the rest of the scrollbar's frame transparent.
- (void)drawRect:(NSRect)dirtyRect {
// Do some custom drawing...
[[NSColor clearColor] set];
NSRectFill(dirtyRect);
// Call NSScroller's drawKnob method (or your own if you overrode it)
[self drawKnob];
}
This is more of a proof of concept than an actual code suggestion (not sure what implications doing this minimal amount of drawing has on the NSScroller.) NSScroller also has other specific drawing methods you can override / call from an overridden drawRect: method (info available from apple's docs: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ApplicationKit/Classes/NSScroller_Class/Reference/Reference.html)
回答2:
If you leave everything out except for drawing the knob you can get a background-less scroller...
- (void) drawRect: (NSRect) dirtyRect
{
[self drawKnob];
}
回答3:
Alternatively, you can use RFOverlayScrollView, a nice subclass of NSScroller which is both transparent and auto-hidden; and published under the MIT License.
RFOverlayScrollView
RFOverlayScrollView is an NSScrollView subclass that shows its NSScroller in iOS style even when a mouse is attached.
回答4:
If you just want to draw on top of what the base class draws, then call [super drawRect:rect]
before you do your own drawing.
FWIW, I'm not sure you'll get the effect you want by drawing on top of NSScroller's default drawing. The iOS style scrollers are semi-transparent. If you call super's drawRect:
, you'll get the blue scrollers which will be visible through the transparent iOS-style scrollers. You probably want to avoid calling super and just draw everything yourself.
If you want to reuse pieces of the drawing NSScroller does, the class provides many methods for doing this, such as drawKnob
, and drawArrow:highlight:
, etc.
来源:https://stackoverflow.com/questions/4181029/how-to-draw-a-transparent-nsscroller