Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I prevent duplicate code inside 2 drawRect: methods?
    primarykey
    data
    text
    <p>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 <code>drawRect</code>: it is called but it is never drawn to the screen. What is the right way prevent duplicating code in two different <code>drawRect</code>: methods?</p> <p>Details: I'm making a custom control by subclassing <code>NSTableView</code> and <code>NSTableCellView</code>. My drawing code needs to be in <code>drawRect</code>: in both of these subclasses.</p> <p>I created a subclass of NSObject that declares one method. Here is the implementation:</p> <pre><code>@implementation TNLChartDrawingExtras - (void)drawDividersInRect:(NSRect)rect startingAtDate:(NSDate *)startDate withZoomFactor:(NSNumber *)zoomFactor { float pos = 0; NSDate *currentDate = [startDate copy]; while (pos &lt; 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]); } } </code></pre> <p>In my NSTableView subclass I define a property for this object. Then in <code>awakeFromNib</code> I create an instance of this class:</p> <pre><code>- (void)awakeFromNib { self.extras = [[TNLChartDrawingExtras alloc] init]; } </code></pre> <p>In <code>drawRect:</code> I send this message:</p> <pre><code>- (void)drawRect:(NSRect)dirtyRect { // more code here... [self.extras drawDividersInRect:viewBounds startingAtDate:chart.startDate withZoomFactor:self.zoomFactor]; } </code></pre> <p>The code is executed but the lines it is supposed to draw don't appear. If I put the code from <code>drawDividersInRect:...</code> in the <code>drawRect:</code> method, it works fine.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload