可可框架中的addSubview
问题描述:
我在窗口中有一个常规的DocumentView类。我有以下的代码,一旦用户按下一个按钮:可可框架中的addSubview
- (void)handleButtonPress:(NSNotification *)note{
// draw new graph view
EDGraphView *graph = [[EDGraphView alloc] init];
[self addSubview:graph];
[self setNeedsDisplay:TRUE];
NSLog(@"Button was pressed");
}
这被称为正确,因为我得到的输出“按下按钮”的每一次点击的按钮。除此之外,视图下方的drawRect方法也会被调用。
- (void)drawRect:(NSRect)dirtyRect
{
NSRect bounds = [self bounds];
[[NSColor whiteColor] set];
[NSBezierPath fillRect:bounds];
for(EDGraphView *graph in [self subviews]){
[graph setNeedsDisplay:TRUE];
NSLog("calling set needs display on graph object!");
}
}
然而,当我走在EDGraphView类和编辑的drawRect方法如下所示
- (void)drawRect:(NSRect)dirtyRect
{
NSLog(@"redrawing graph view.");
}
它永远不会被调用!我必须错过整个setNeedsDisplay和drawRect过程。
有什么建议吗?
答
明白了...我需要让我的子视图下的init电话:
EDGraphView *graph = [[EDGraphView alloc] initWithFrame:bounds];
现在它调用drawRect方法!
答
嗨你可能不会把setneeddisplay称为drawrect。
你有没有试过(用超级)? :
- (void)drawRect:(NSRect)dirtyRect
{
NSRect bounds = [self bounds];
[[NSColor whiteColor] set];
[NSBezierPath fillRect:bounds];
[super drawRect:rect];
}
感谢divot但没有运气。我在子视图上调用setNeedDisplay的原因是让他们知道他们也需要调用drawRect。 – schmudu 2012-07-22 21:28:56
通常,如果父视图需要更新其所有子视图,则不需要将子视图上的setNeedDisplay调用为drawrect。只要你专门设计了一个drawRect,它就会被调用。 – divol 2012-07-23 07:22:32