I have a few lines of drawing code that are duplicated in two different subclasses. When I move this drawing code to its own class and then call it from within drawRect
: it is called but it is never drawn to the screen. What is the right way prevent duplicating code in two different drawRect
: methods?
Details: I'm making a custom control by subclassing NSTableView
and NSTableCellView
. My drawing code needs to be in drawRect
: in both of these subclasses.
I created a subclass of NSObject that declares one method. Here is the implementation:
@implementation TNLChartDrawingExtras
- (void)drawDividersInRect:(NSRect)rect startingAtDate:(NSDate *)startDate withZoomFactor:(NSNumber *)zoomFactor {
float pos = 0;
NSDate *currentDate = [startDate copy];
while (pos < rect.size.width) {
//draw the vertical divider
NSBezierPath *linePath = [NSBezierPath bezierPathWithRect:NSMakeRect(pos, 0.0, 1.0, rect.size.height)];
[[NSColor colorWithCalibratedWhite:0.85 alpha:0.5] set];
[linePath fill];
//increment the values for the next day
currentDate = [NSDate dateWithTimeInterval:86400 sinceDate:currentDate]; // add one day to the current date
pos = pos + (86400.0/ [zoomFactor floatValue]);
}
}
In my NSTableView subclass I define a property for this object. Then in awakeFromNib
I create an instance of this class:
- (void)awakeFromNib {
self.extras = [[TNLChartDrawingExtras alloc] init];
}
In drawRect:
I send this message:
- (void)drawRect:(NSRect)dirtyRect {
// more code here...
[self.extras drawDividersInRect:viewBounds startingAtDate:chart.startDate withZoomFactor:self.zoomFactor];
}
The code is executed but the lines it is supposed to draw don't appear. If I put the code from drawDividersInRect:...
in the drawRect:
method, it works fine.