2016-07-20 40 views
1

我的ui結構就像NSWindow - > NSViewController - > NSView(父) - > NSView(目標視圖)。 目標視圖是從XIB文件拖動而不是addSubview。當顯示NSView(父級)時,將調用drawRect函數,但在此之後,我想以setNeedsDisplay以編程方式再次調用drawRect,它不起作用。 我的方法有什麼問題?drawRect不用setNeedsDisplay調用

無論如何,我可以使用drawRect(view.frame)來實現這一點,但我認爲這不是一個好主意。

代碼:

MyView.m 

- (void)drawRect:(NSRect)dirtyRect { 
    [super drawRect:dirtyRect]; 

    NSLog(@"asasa"); 
} 

... 
@property (weak) IBOutlet MyView *titleBarView; 
... 

-(IBAction)test:(id)sender 
{ 
    NSLog(@"%@",self.view.subviews); // contains the titleBarView 
    NSLog(@"%@",self.titleBarView); // not nil 
    [self.titleBarView setNeedsDisplay:YES]; // not call drawRect 
} 

titleBarView已經連接

+0

你叫目標視圖的'setNeedsDisplay'嗎? – bluedome

+0

@bluedome,是的,我叫setNeedsDisplay,但它不起作用 – jimwan

+0

顯示調用'setNeedsDisplay:'的代碼。另外,你確定你是按照你認爲自己的觀點來稱呼它的嗎?那是父母還是目標?難道是因爲你沒有正確地連接某些東西(例如插座),你對該視圖的引用是「無」的?切勿調用'drawRect';它不會正常工作。 –

回答

1

你現在正在做將引發self.titleBarViewdrawRect:,而不是self.view。要觸發self.view(具有NSLog聲明的那個)的drawRect:,請致電setNeedsDisplayself.view

- (void)drawRect:(NSRect)dirtyRect { 
[super drawRect:dirtyRect]; 

NSLog(@"asasa"); 
} 

... 
@property (weak) IBOutlet MyView *titleBarView; 
... 

-(IBAction)test:(id)sender 
{ 
    NSLog(@"%@",self.view.subviews); // contains the titleBarView 
    NSLog(@"%@",self.titleBarView); // not nil 
    [self.titleBarView setNeedsDisplay:YES]; // this triggers the drawRect: method of self.titleBarView 
    [self.view setNeedsDisplay:YES]; // this triggers your drawRect: method with he NSLog statement 
} 
+0

問題是'[self.titleBarView setNeedsDisplay:YES]'不調用drawRect:self.titleBarView的方法 – jimwan

+0

哦。嗯。你確定self.titleBarView被添加到視圖層次? –

+0

我發現了根本原因,我使用'CAGradientLayer * gradientLayer = [CAGradientLayer層];''self.layer = gradientLayer;'在drawRect函數中,但我不知道爲什麼這個代碼會導致這個問題 – jimwan

相關問題