2011-12-02 86 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