3

I'm trying to create a simple drawing app that creates circles wherever you put your finger, this is what I have:

@synthesize touchPos;
@synthesize coords;


- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    touchPos = [touch locationInView:self.view];
    coords.text = [NSString stringWithFormat:@"%3.0f, %3.0f", touchPos.x, touchPos.y];
    [self setNeedsDisplay];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self touchesBegan:touches withEvent:event];
}

- (void)drawRect:(CGRect)rect
{
    CGContextRef contextRef = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(contextRef, 2.0);
    CGContextSetRGBFillColor(contextRef, 0, 0, 1.0, 1.0);
    CGContextSetRGBStrokeColor(contextRef, 0, 0, 1.0, 1.0);
    CGRect circlePoint = (CGRectMake(touchPos.x, touchPos.y, 10.0, 10.0));

    CGContextFillEllipseInRect(contextRef, circlePoint);
}

I don't get any errors or warnings, it just doesn't draw anything. Also, the text box shows the coordinates wherever I'm touching, so I know that's not the problem.

Paul R
  • 208,748
  • 37
  • 389
  • 560
kyle
  • 31
  • 1
  • 2

3 Answers3

3

This code needs to be in a UIView subclass that is part of the current view hierarchy.

hotpaw2
  • 70,107
  • 14
  • 90
  • 153
  • I added a subclass, but drawRect isn't getting called, so nothing gets drawn. – kyle Jul 23 '11 at 16:44
  • 1
    Did you create and add an instance of your view subclass to your current view hierarchy? (alloc, initWithXYZ, addSubView, etc.) Are that view's touch handlers getting called? – hotpaw2 Jul 23 '11 at 17:32
1

Did you call addSubview to add this to the main view? Did you call setNeedsDisplay for this view?

See also this SO question.

Make sure the frame is correct and within the bounds of the parent view.

Community
  • 1
  • 1
progrmr
  • 75,956
  • 16
  • 112
  • 147
0

The issue is that -drawRect: isn't being called because, that's right, your writing this code in a UIViewController. You need to make a subclass of UIView and move all of this drawing and event handling to it. The only thing that you should need to change is self.view, since in a subclass of UIView you will just need to say self. Once you have a custom UIView subclass, you can use interface builder to set the class of your UIViewController to your custom class.

Alex Nichol
  • 7,512
  • 4
  • 32
  • 30