Question

I draw an initial simple rect using UIBezierPath and fill it with color. How can I change only its color by touching on it?

- (void) drawRect:(CGRect)rect
{
    // Drawing code
    [self drawRectWithFrame:_myRect fillColor:_firstColor];
}
- (void) drawRectWithFrame:(CGRect)frame fillColor:(UIColor *)color
{
    [color setFill];
    UIBezierPath *path = [UIBezierPath bezierPathWithRect:frame];
    [path fill];
}
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    //get the rect color from touches (pixel color)     
    UIColor *color = [self getRectColorFromTouches:touches];

    //chnage the rect color
    if (color == _firstColor) {

    //doesn't work
    //[self drawRectWithFrame:_myRect fillColor:_secondColor]; //??
        //How can I do that?
    }
    else {
        //??
    }    
}
Was it helpful?

Solution

Some remarks :

  • Instead of overriding UIView touch event methods, you should use a UIGestureRecognizer. In your case, a UItapGestureRecognizer might be enough. (this way, it will be easier to handle conflict between different touch actions, that's the reason why gestureRecognizers were created!)

  • When you receive tap, change a local property of your view (for example, a BOOL isRectangleDrawn might be changed each time the view receives the tap)

  • Finally - and that's what missing in your code, that otherwise should be correct - don't forget to call [self setNeedsDisplay] to be sure your view's - (void) drawRect:(CGRect)rect method gets called

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