Question

I have a nsscroll view in my application and i made a subclass of nsscrollview to add a nsgradient but it doesn't work this is my code in my implementation file:

#import "scrollview.h"
@implementation scrollview
@synthesize startingColor;
@synthesize endingColor;
@synthesize angle;

- (id)initWithFrame:(NSRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code here.
        [self setStartingColor:[NSColor colorWithCalibratedRed:0.941 green:0.941 blue:0.941 alpha:1]];
        [self setEndingColor:[NSColor colorWithCalibratedRed:0.6588 green:0.6588 blue:0.6588 alpha:1]];


        [self setAngle:90];
    }
    return self;
}

- (void)drawRect:(NSRect)rect {

    NSBezierPath* roundRectPath = [NSBezierPath bezierPathWithRoundedRect: [self bounds] xRadius:10 yRadius:10]; 
    [roundRectPath addClip];
    if (endingColor == nil || [startingColor isEqual:endingColor]) {
        // Fill view with a standard background color
        [startingColor set];
        NSRectFill(rect);
    }
    else {
        // Fill view with a top-down gradient
        // from startingColor to endingColor
        NSGradient* aGradient = [[NSGradient alloc]
                                 initWithStartingColor:startingColor
                                 endingColor:endingColor];
        [aGradient drawInRect:[self bounds] angle:angle];
    }
}
Was it helpful?

Solution

The first step is to create a custom NSView subclass that draws a gradient:

GradientBackgroundView.h:

@interface GradientBackgroundView : NSView
{}
@end

GradientBackgroundView.m:

#import "GradientBackgroundView.h"
@implementation GradientBackgroundView    
- (void) drawRect:(NSRect)dirtyRect
{
    NSGradient *gradient = [[[NSGradient alloc] initWithStartingColor:[NSColor redColor] endingColor:[NSColor greenColor]] autorelease];
    [gradient drawInRect:[self bounds] angle:90];
}
@end

The next step is to make the scroll view's document view an instance of this class (instead of plain NSView).

In IB, double-click your scroll view, and in the Identity pane set the Class to GradientBackgroundView.

From this point on, things are handled pretty much in the standard way. You can add subviews to the document view, resize it, etc. Here's a screenshot: Gradient background

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top