2011-12-02 88 views
0

我試圖添加一個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]; 
} 

預先感謝您的幫助。

+0

您是否收到「DataSource conforms ...」消息? – Chuck

+0

不,那是我的另一個問題。 –

+0

我已經在我的視圖控制器中添加了代碼給awakeFromNib方法,該方法應該設置DataSource以符合我的協議,但由於某種原因它什麼都不做。 –

回答

0

這聽起來很像你的數據源是零。有幾個可能性:

  1. 你忘了把它掛在Interface Builder

  2. 它不是通過界面生成器連接,而是通過另一個控制器 - 但類(控制器)具有在Interface Builder缺少的連接

  3. 你根本忘了給它分配

從應該設置數據源的地方向前追蹤以確定監管鏈消失的位置。

+0

你是對的我測試了看它是否爲零,這是我無法弄清楚爲什麼。 –

+0

當你說我可能忘記在Interface Builder中掛鉤它時,你是什麼意思。 –

+0

@SageWashabaugh:我不知道數據源應該如何連接。如果要在Interface Builder中建立連接,可能無法建立連接。如果它應該是在代碼中,也許這個代碼在你認爲是沒有得到運行。我要說的是,開始分配數據源的位置,確保實際發生,然後繼續前進,直到看到它消失的位置。 – Chuck