macoscocoanswindownsgradient

how to set NSGradient to NSWindow background


I am new to cocoa I am try to set NSGradient to the NSWindow background but it's too difficult for me...I have try this code

NSGradient *gradient = [[NSGradient alloc] initWithStartingColor:[NSColor orangeColor] endingColor:[NSColor lightGrayColor]];
NSRect windowFrame = [self frame];
[gradient drawInRect:windowFrame angle:90];

but it is not working.... any other way to set NSGradient to NSWindow....


Solution

  • You can do it by subclassing NSWindow's View.

    Create new window view's class (For example with title WindowViewSubclass).

    Then .h file should look like this:

    #import <Cocoa/Cocoa.h>
    
    @interface WindowViewSubclass : NSView {
    
    }
    
    @end
    

    and .m file:

    #import "WindowViewSubclass.h"
    
    @implementation WindowViewSubclass
    
    - (void)drawRect:(NSRect)dirtyRect
    {
        NSGradient *gradient = [[NSGradient alloc] initWithStartingColor:[NSColor orangeColor] endingColor:[NSColor lightGrayColor]];
        NSRect windowFrame = [self frame];
        [gradient drawInRect:windowFrame angle:90];
    }
    
    @end
    

    Now select window's view and go to Identity Inspectory -> Custom Class -> and select class like this:

    Screenshot

    Result:

    Result image