2011-09-13 100 views
1

我的問題是,當動作UpdateRect調用drawRect方法時,我的矩形不會更新高度!問題繪製NSRect

當我點擊按鈕時,我期望看到我的矩形高度爲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 

回答

6

您不應該自己撥打drawRect:。相反,調用setNeedsDisplay:

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

注:相當於iOS版是setNeedsDisplay沒有一個說法。

+0

哦!謝謝 !但請你可以帶我的代碼並插入「[self setNeedsDisplay:YES];」 ?我擔心把它放在錯誤的地方;) – Alberto

+4

來吧,現在。我們不要懶惰,阿爾貝託。要做的更好的事情是閱讀相關的文檔,因爲你知道你有一個基本的Cocoa繪圖概念。以下是您真正需要閱讀的指南**:http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CocoaDrawingGuide/Introduction/Introduction.html –

+0

解決了它!謝謝 ! – Alberto