objective-ccocoansgradient

NSScrollView messes up NSGradient (corruption)


I have a custom box that I've made that is a subclass of NSBox. I override the drawRect: method and draw a gradient in it like this (assuming I already have a start & end color):

-(void)drawRect:(NSRect)dirtyRect {
    NSGradient *gradient = [[NSGradient alloc] initWithStartingColor:start endingColor:end];
    [gradient drawInRect:dirtyRect angle:270];
    [gradient release];
}

Now this box is added as a subview of a prototype view for a NSCollectionView. In the view's original state it looks like this:

enter image description here

And after scrolling the view out of sight and back in again, it looks like this:

enter image description here

Why is my gradient getting corrupted like that, and how can I fix it? Thanks!


Solution

  • Your problem is you're drawing in dirtyFrame, not the entire rectangle of the box. I have no idea if this is correct, but try this:

    -(void)drawRect:(NSRect)dirtyRect {
        NSGradient *gradient = [[NSGradient alloc] initWithStartingColor:start endingColor:end];
        [gradient drawInRect:[self bounds] angle:270];
        [gradient release];
    }