Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want a circle to be drawn when the user clicks anywhere on the screen. Whats missing/is wrong with this code?

- (void)drawRect:(CGRect)rect
{
if (UITouchPhaseBegan)
{
    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);
}

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
193 views
Welcome To Ask or Share your Answers For Others

1 Answer

Your code doesn’t do what you think it does. Have a look at the definition of UITouchPhaseBegan in UITouch.h:

typedef NS_ENUM(NSInteger, UITouchPhase) {
    UITouchPhaseBegan,             // whenever a finger touches the surface.
    UITouchPhaseMoved,             // whenever a finger moves on the surface.
    UITouchPhaseStationary,        // whenever a finger is touching the surface but hasn't moved since the previous event.
    UITouchPhaseEnded,             // whenever a finger leaves the surface.
    UITouchPhaseCancelled,         // whenever a touch doesn't end but we need to stop tracking (e.g. putting device to face)
};

It’s just an enum value, not a reflection of what is going on in your app. I believe that in this case, because it is the first value in the enum, it is probably being set to 0 by the compiler, and is therefore always evaluating to false.

What you probably want to do is to set an ivar like BOOL _touchHasbegun;. Then, in -touchesBegan:withEvent or your gesture recognizer action, depending on how you’re doing touch handling, set _touchHasBegun to YES or NO as appropriate.

When you know your view needs to be updated, call [self setNeedsDisplay] (or [self setNeedsDisplayInRect:someRect] if you can, for better performance) to trigger the -drawRect: method. Then, have your -drawRect: method check whether _touchHasBegun to determine whether to draw your circle.

Note: You should never call -drawRect: yourself. You set the view as dirty, and the OS takes care of drawing it at the right time.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...