我有幾行在兩個不同的子類中複製的繪圖代碼。當我將這個繪圖代碼移動到它自己的類中,然後從drawRect
中調用它時:它被調用,但它永遠不會繪製到屏幕上。什麼是正確的方法防止在兩個不同的drawRect
:方法中重複代碼?如何防止2 drawRect:方法內的重複代碼?
詳情:我正在通過繼承NSTableView
和NSTableCellView
進行自定義控制。我的繪圖代碼需要在drawRect
:這兩個子類中。
我創建了一個聲明一個方法的NSObject的子類。這裏是執行:
@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]);
}
}
在我的NSTableView子類中,我爲這個對象定義一個屬性。然後在awakeFromNib
我創建這個類的一個實例:
- (void)awakeFromNib {
self.extras = [[TNLChartDrawingExtras alloc] init];
}
在drawRect:
我發這條短信:
- (void)drawRect:(NSRect)dirtyRect {
// more code here...
[self.extras drawDividersInRect:viewBounds startingAtDate:chart.startDate withZoomFactor:self.zoomFactor];
}
被執行的代碼,但該行是應該汲取不會出現。如果我將drawDividersInRect:...
的代碼放在drawRect:
方法中,它可以正常工作。
您應該添加一些代碼,以便我們可以看到您正在嘗試的內容。 – Matt
你檢查過'self.extras'不是'nil'嗎?這將解釋它。 – djromero