开发者

Cocoa / Objective-C: Draw Rectangle on Button Click

Hellow stackoverflow people, I am pretty new to Cocoa. I have XCode 3.1

Situation: I have a NSObject subclass: (AppController) with an action, linked to a button. Than i have a custom View, connected to my NSView subclass (AppView), in the drawRect command i draw a rectangle (all that stuff works), i have in the AppView.m a function - (void) drawIt { .. } which draws the rectangle. For now i called it in the - (void) drawRect ... with [self drawIt]. That works too.

What i want to do now is to call drawIt when the button is clicked. (in the AppController.m when the Action -(IBAction) ... is called due to a button Click)

I hope u can help me, I am new开发者_运维问答 to stackoverflow so i dont know wether i should past all the code here, i can but maybe its easier to read like this


You should read the Cocoa Drawing Guide conceptual material. Your view is asked to -drawRect: by the system when the system feels it's necessary. In that regard, your view can be asked to draw itself at any time. Therefore, you have to think of this in terms of "drawing the current state".

What you should probably do (in this basic situation) is perhaps give your custom view a boolean property "drawIt" and have your button action toggle this on the view instance. This way if (self.drawIt == YES), you can call your rectangle-drawing code.

You should always do something to "clear" the view when -drawRect: is called (like fill the whole bounds with white), then only draw the conditional stuff if the condition is met.

Example:

- (void)drawRect:(NSRect)aRect
{
  // Clean up background (we ignore "aRect", drawing entire view at once)
  [[NSColor whiteColor] set];
  NSRectFill([self bounds]);

  // Do we want to draw our magic rect?
  if ([self drawMagicRect])
  {
    [[NSColor redColor] set];
    NSRectFill([self magicRect]);
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜