Question

I have a UIView subclass called MENode. Each MENode has a NSMutableDictionary that keeps track of its subnodes (also MENodes). What I am trying to achieve is drawing a line from the parent node to the child node. This is my implementation of drawRect: in 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);
    }
}

Both of the Below methods are called by the View Controller. I call [self setNeedsDisplay]; in both:

-(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;
}

When I run this I get no lines, just the nodes. Thanks in advance for your help.

Was it helpful?

Solution

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

self.center is in the view's superview's coordinate space, so that could be part of the problem. Try this:

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

You may also want to set a breakpoint in your drawing code to ensure that self.subNodes actually has objects at the time drawing executes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top