如何用线连接两个UIViews?

时间:2014-01-30 21:11:18

标签: objective-c cocoa-touch uiview setneedsdisplay uigraphicscontext

我有一个名为MENode的UIView子类。每个MENode都有一个NSMutableDictionary,用于跟踪其子节点(也是MENode s)。我想要实现的是从父节点到子节点绘制一条线。这是drawRect:MENode的实现:

- (void)drawRect:(CGRect)rect{
//connect the sub node to its super node by drawing a line between the two;

    for (int i=0; i<self.subNodes.count; i++) {
        //get one of the child nodes
        MENode *subNode = [self.subNodes objectAtIndex:i];

        //get the context and set up color and line width
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor);
        CGContextSetLineWidth(context, 5);

        //set up a line between the parent node and the child node
        CGContextMoveToPoint(context, self.center.x, self.center.y);
        CGContextAddLineToPoint(context, subNode.center.x, subNode.center.y);

        //draw it.
        CGContextStrokePath(context);
    }
}

以下两种方法都由View Controller调用。我在两个地方都打电话给[self setNeedsDisplay];

-(void)addNode:(MENode *)newNode{
    //set the child node's parent node to self (a weak reference)
    newNode.parentNode = self;

    //add the node to self.subNodes
    [self.subNodes addObject:newNode];

    //add the node to the parent node
    [self addSubview:newNode];

    //call seeNeedsDisplay
    [newNode setNeedsDisplay];
}

-(void)nodeAdditionsDone{
    //call setNeedsDisplay
    [self setNeedsDisplay];

    //do some logic with this later
    self.nodeAddtionsAreFinished = YES;
}

当我运行这个时,我没有线,只有节点。在此先感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

CGContextMoveToPoint(context, self.center.x, self.center.y);

self.center位于视图的 superview 的坐标空间中,因此可能是问题的一部分。试试这个:

CGContextMoveToPoint(context, CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds))

您可能还想在绘图代码中设置断点,以确保self.subNodes在绘图执行时实际上有对象。