Search code examples
xcodecocoansrect

setNeedsDisplay for DrawRect after button press


I have this in a custom class on my NSView and when I press a button using my drawMyRec IBAction I want to change the color of my NSRect however this is not working, can anyone help?

#import "myView.h"

@implementation myView

- (id)initWithFrame:(NSRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        RectColor = [[NSColor blackColor] init];
    }

    return self;
}


- (IBAction)drawMyRec:(id)sender;
{
    NSLog(@"pressed");
    RectColor = [[NSColor blueColor] init];
    [self setNeedsDisplay:YES];
}


- (void)drawRect:(NSRect)dirtyRect
{
    NSRectFill(dirtyRect);
    [RectColor set];

}

@end

Solution

  • Your drawRect function is incorrect. change to this:

    - (void)drawRect:(NSRect)dirtyRect
    {
        [RectColor set];
        NSRectFill(dirtyRect);
    
    }