绘制NSRect的问题

1 cocoa objective-c drawrect

我的问题是,当UpdateRect操作调用drawRect方法时,我的rect不会更新高度!

当我点击按钮时,我希望看到我的矩形高度为20,但它仍然是10.为什么?

@implementation Graphic_view

int height = 10; //The height of my rect.

-(IBAction)updateRect:(id)sender {
    height += 10;
    //Calling the drawrect method
    [self performSelector:@selector(drawRect:)];
}

-(void)drawRect:(NSRect)dirtyRect {
    NSLog(@"DrawRect has been called !");
    // Drawing code here.
    NSRect viewBounds = [self bounds];
    NSColor *color = [NSColor orangeColor];
    [colore set];
    NSRectFill(viewBounds);
    NSRect myRect;
    myRect.origin.x = 20;
    myRect.origin.y = 20;
    myRect.size.height = height;
    myRect.size.width = 100;
    NSColor *whiteColor = [NSColor whiteColor];
    [whiteColor set];
    NSRectFill(myRect);
} 

@end
Run Code Online (Sandbox Code Playgroud)

Mat*_*ats 7

你永远不应该打电话给drawRect:自己 而是打电话setNeedsDisplay:

-(IBAction)updateRect:(id)sender {
    height += 10;
    // Schedule the drawrect method
    [self setNeedsDisplay:YES];
}
Run Code Online (Sandbox Code Playgroud)

注意:iOS等价物setNeedsDisplay没有参数.

  • 来吧,现在.阿尔贝托,我们不要懒惰.最好的办法是阅读相关文档,因为你知道有一个你缺少的基本Cocoa绘图概念.这是你真正需要阅读的指南**:http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CocoaDrawingGuide/Introduction/Introduction.html (4认同)