2014-06-10 44 views
0

我正在繪製一個非結構化二叉樹。我現在遇到的問題是,當我構建應用程序時,它會始終進入無限循環,創建新的nodeView對象。繪圖視圖保持在drawRect中無限地實例化新子視圖Objective-c OSX

我是新來的programatic繪圖。我知道我正在犯一些可能相當明顯的基本錯誤。什麼是最好的方式來繪製我的NSView的樹,而不是不斷重新實例化這些。

理想情況下,我希望能夠拖放NSView節點。我可以在以後看到這些信息,以防萬一它有幫助。

- (void)drawRect:(NSRect)dirtyRect { 
    if (!hasSetUp) [self setUp]; 
    [super drawRect:dirtyRect]; 

    DTNodeView *nodeView = [[DTNodeView alloc] initWithFrame:NSMakeRect(200, 200, 100, 100)]; 
    //[self addSubview:nodeView]; 


    [[NSColor yellowColor] set]; 
    NSRectFill([self frame]); 

    //NSLog(@"Subviews are: %@", [self.window.contentView subviews]); 

    NSLog(@"Left tree height: %i", leftTree.treeHeight); 

    double deltaY = (self.window.frame.size.height/2)/([leftTree treeHeight] + 1); 
    [self drawSubtreeFromNode:[leftTree root] yValue:self.window.frame.size.height - 100 yDecrement:deltaY leftBound:0 rightBound:self.window.frame.size.width/2]; 

    // Drawing code here. 
} 

-(void)drawSubtreeFromNode:(DTNode *)node yValue:(double)y yDecrement:(double)deltaY leftBound:(double)left rightBound:(double)right { 

    double x = (left + right)/2; // Draw the node in between the parents 

    DTNodeView *selfRoot = [[DTNodeView alloc] initWithFrame:NSMakeRect(x, y, 100, 50) andNode:node]; 
    [self addSubview:selfRoot]; 

    if ([node hasLeft]) { 
     double y2 = (y - deltaY); 
     double x2 = (left + ((left + right)/2))/2; 


     [[NSColor redColor] set]; 
     NSBezierPath *line = [[NSBezierPath alloc] init]; 
     [line setLineWidth:2]; 
     [line moveToPoint:NSMakePoint(x, y)]; 
     [line lineToPoint:NSMakePoint(x2, y2)]; 
     [line stroke]; 

     //drawSubtree(node.getLeft(), y-yDecrement, yDecrement, left, ((left + right)/2)); 
     [self drawSubtreeFromNode:[node left] yValue:(y - deltaY) yDecrement:deltaY leftBound:left rightBound:((left + right)/2)]; 

    } 

    if ([node hasRight]) { 
     double x2 = (right + ((left + right)/2))/2; 
     double y2 = (y - deltaY); 

     [[NSColor redColor] set]; 
     NSBezierPath *line = [[NSBezierPath alloc] init]; 
     [line setLineWidth:2]; 
     [line moveToPoint:NSMakePoint(x, y)]; 
     [line lineToPoint:NSMakePoint(x2, y2)]; 
     [line stroke]; 


     //drawSubtree(node.getRight(), y-yDecrement, yDecrement, ((left + right)/2), right); 
     [self drawSubtreeFromNode:[node right] yValue:(y - deltaY) yDecrement:deltaY leftBound:((left + right)/2) rightBound:right]; 

    } 

} 

回答

2

在drawRect方法,你應該畫而已。這不是創建視圖並將其添加到其超級視圖的地方。很明顯,添加子視圖意味着需要重畫視圖,然後創建新的子視圖等。等等。

+0

所以我應該創建一個方法來實例化子視圖,然後在draw方法中調用addSubview:所有這些? – SeniorShizzle

+0

是的,您需要預先爲繪圖預先創建所需的所有對象(init,layoutSubviews或任何您喜歡的),以使繪圖儘可能保持高性能。 –