Link
Link

Reputation: 3

My subclass of NSView will not refresh / redraw but -drawRect is called

I have a simple test application that I am having problems with. the UI is two slider (x & y) and a Custom view that i draw a red dot on. Right now the the dot will show up at the initial position but will not move with the sliders. Using NSLog i can tell that when i move the sliders that drawRect is geting called and the x and y data is current. My subclass of NSView:

#import <Cocoa/Cocoa.h>


@interface BallView : NSView {
    NSRect rect;
    NSBezierPath *bp2;
}
@property (readwrite) NSRect rect;
@end

#import "BallView.h"


@implementation BallView
@synthesize rect;
- (id)initWithFrame:(NSRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code here.
    rect = NSMakeRect(50, 10, 10, 10);

    }
    return self;
}


- (void)drawRect:(NSRect)dirtyRect {
    NSLog(@"draw rect: %f, %f", rect.origin.x, rect.origin.y);
    bp2 = [NSBezierPath bezierPath]; 
    [bp2 appendBezierPathWithOvalInRect: rect];
    NSColor *color2 = [NSColor redColor];
    [color2 set];
    [bp2 fill]; 
}

To get the slider values to In the app delegate rect :

-(IBAction) setX:(id)sender{
x=[sender floatValue];
[ballView setRect: NSMakeRect(x, y, 10, 10)];
NSLog(@"set x");
}

-(IBAction) setY:(id)sender{
    y= [sender floatValue];
    [ballView setRect: NSMakeRect(x, y, 10, 10)];
    NSLog(@"set y");
}

Upvotes: 0

Views: 3742

Answers (1)

febeling
febeling

Reputation: 1464

You don't tell the view that it needs redrawing. Put

[ballView setNeedsDisplay:YES];

into the state-mutating actions. I would generally implement setters for this purpose and have them call this from inside the view, instead of synthesizing it.

Upvotes: 1

Related Questions