I’m trying to draw a line between one object and where the user touched. I’ve tried subclassing and I can’t get the “-(void)drawrect” to update itself every time the user touches the screen. I deleted those files and tried putting the code right into the “-(void)touchesbegan”, but it does not WORK:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
UITouch *touch = [touches anyObject];
CGPoint locationOfTouch = [touch locationInView:nil];
// You can now use locationOfTouch.x and locationOfTouch.y as the user's coordinates
Int xpos = (int)(starShip.center.x);
int ypos = (int)(starShip.center.y);
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 5.0);
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 0.0, 0.0, 0.0, 1.0);
CGContextBeginPath(UIGraphicsGetCurrentContext());
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), starShip.center.x, starShip.center.y);
//draws a line to the point where the user has touched the screen
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), locationOfTouch.x, locationOfTouch.y);
CGContextStrokePath(UIGraphicsGetCurrentContext());
}
drawRect:is only called when required. It’s called automatically the first time the view is displayed and every time the view is resized. If you want it to be called after a touch you have to call[self setNeedsDisplay];.This will make sure the
drawRect:method will be called. You don’t directly calldrawRect:, because it you called it multiple times in one frame, the view would redraw itself multiple times. Instead you flag it as needing a redraw usingsetNeedsDisplay. This waydrawRect:will only be called once, no matter how often you callsetNeedsDisplay.