0

This is my code:

@implementation myView2
{
BOOL _touchHasBegun;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
_touchHasBegun = YES;
}

- (void)drawRect:(CGRect)rect
{
if (_touchHasBegun == YES)
{
    NSLog(@"fjnv");
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetRGBStrokeColor(context, 0, 0, 225, 1);
    CGContextSetRGBFillColor(context, 0, 0, 255, 1);
    CGRect rectangle = CGRectMake(50, 50, 500, 500);
    CGContextStrokeEllipseInRect(context, rectangle);
}
}

I have also tried with a UIButton on top of the UIView and set the CGRect in the button action method. But that doesn't work. Nor does this code. What's wrong?

Nathaniel Waisbrot
  • 23,261
  • 7
  • 71
  • 99

1 Answers1

0

Here is a working snippet :

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    _touchHasBegan = YES;
    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect
{
    if(_touchHasBegan){
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetRGBStrokeColor(context, 0, 0, 225, 1);
        CGContextSetRGBFillColor(context, 0, 0, 255, 1);
        CGRect rectangle = self.bounds;
        CGContextStrokeEllipseInRect(context, rectangle);
    }
}
Alexis C.
  • 4,898
  • 1
  • 31
  • 43
  • thanks! was the only problem in the if statement? – Wilhelm Michaelsen Feb 27 '13 at 12:19
  • No, the main issue was that you have to call setNeedsDisplay to notify the system that you want it to call drawRect as soon as it's possible. You can check my answer (little checkmark) if it solved your problem by the way. – Alexis C. Feb 27 '13 at 14:45