我試圖添加一個NSRect時推按鈕,但IBAction是在一個視圖控制器,而繪圖代碼必須在視圖中,由於某種原因我使用的代碼贏得'牛逼得出這裏的矩形是在視圖控制器的操作方法來源:當按鈕被按下時添加一個NSRect
-(IBAction)ButtonPressed:(id)sender {
NSRect Rect = NSMakeRect(10, 10, 100, 100);
NSColor* BlackFill = [NSColor blackColor];
[BlackFill set];
NSRectFill(Rect);
NSColor* whitestroke = [NSColor whiteColor];
[whitestroke set];
NSFrameRectWithWidth(Rect, 5.0);
[rects addObject:[NSValue valueWithRect:Rect]];
[self.rectView setNeedsDisplay:YES];
}
而對於在視圖中繪製代碼來源:
-(void)drawRect:(NSRect)dirtyRect {
//heres the part where I want to draw the NSRect but it does not work
if ([datasource conformsToProtocol:@protocol(MainViewDatasource)]) {
NSLog(@"DataSource conforms to protocol:MainViewDatasource");
NSUInteger numRects = [datasource numberOfRectsInView:self];
for (NSUInteger i = 0; i < numRects < 800; i++) {
NSRect currentRect = [datasource rectangleView:self rectAtIndex:i];
NSFrameRect(currentRect);
}
if (numRects >= 800) {
NSAlert* alert = [[NSAlert alloc] init];
[alert setAlertStyle:NSInformationalAlertStyle];
[alert setMessageText:@"You have placed too many rectangle shapes in your level"];
[alert addButtonWithTitle:@"OK"];
[alert release];
}
}
/* The code here works great but has nothing to do with adding a rect when the button is pressed */
NSRect Rect = NSMakeRect(0.0, 0.0, 7000.0, 3500.0);
int width = Rect.size.width;
int height = Rect.size.height;
int i = 0;
[[NSColor blackColor] set];
NSBezierPath* drawingPath = [NSBezierPath bezierPath];
for (i=0; i<=width; i=i+GRIDSIZE) {
[drawingPath moveToPoint:NSMakePoint(i, 0)];
[drawingPath lineToPoint:NSMakePoint(i, height)];
}
for (i=0; i<=height; i=i+GRIDSIZE) {
[drawingPath moveToPoint:NSMakePoint(0, i)];
[drawingPath lineToPoint:NSMakePoint(width, i)];
}
[drawingPath stroke];
}
預先感謝您的幫助。
您是否收到「DataSource conforms ...」消息? – Chuck
不,那是我的另一個問題。 –
我已經在我的視圖控制器中添加了代碼給awakeFromNib方法,該方法應該設置DataSource以符合我的協議,但由於某種原因它什麼都不做。 –