Grant Wilkinson
Grant Wilkinson

Reputation: 1128

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

Upvotes: 0

Views: 1210

Answers (2)

Justin Boo
Justin Boo

Reputation: 10198

Your drawRect function is incorrect. change to this:

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

}

Upvotes: 2

user1118321
user1118321

Reputation: 26375

First, why are you calling -init on an NSColor? Second, you're setting the color after you've drawn the rect, so it won't take affect until the next redraw. 3rd, what's dirtyRect when -drawRect: is called? Why not just fill the entire rect regardless of what's dirty?

Upvotes: 2

Related Questions