按下按钮时添加NSRect

时间:2011-12-02 03:14:48

标签: objective-c xcode macos

我正在尝试在按下按钮时添加NSRect但是IBAction在一个视图控制器中,而绘图代码必须在视图中,并且由于某种原因我正在使用的代码不会在这里绘制矩形是源对于视图控制器中的action方法:

-(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];
}

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

听起来非常像你的数据源是零。一些可能性:

  1. 您忘了在Interface Builder

  2. 中将其挂钩
  3. 它没有通过Interface Builder连接,而是通过另一个控制器连接 - 但 类(控制器)在Interface Builder中缺少连接

  4. 您只是忘了分配

  5. 从应该设置数据源的位置向前追踪,以找出监管链消失的位置。