iOS Detect tap down and touch up of a UIView

前端 未结 5 2110
忘掉有多难
忘掉有多难 2020-12-01 05:06

I am stuck with a problem of determining how to detect a UIView being touched down and UIView being tapped. When it is touched down, I want the UIView to change its backgrou

5条回答
  •  鱼传尺愫
    2020-12-01 05:52

    A Gesture Recognizer is probably overkill for what you want. You probably just want to use a combination of -touchesBegan:withEvent: and -touchesEnded:withEvent:.

    This is flawed, but it should give you and idea of what you want to do.

    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    {
        self.touchDown = YES;
        self.backgroundColor = [UIColor redColor];
    }
    
    - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
    {
        // Triggered when touch is released
        if (self.isTouchDown) {
            self.backgroundColor = [UIColor whiteColor];
            self.touchDown = NO;
        }
    }
    
    - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
    {
        // Triggered if touch leaves view
        if (self.isTouchDown) {
            self.backgroundColor = [UIColor whiteColor];
            self.touchDown = NO;
        }
    }
    

    This code should go in a custom subclass of UIView that you create. Then use this custom view type instead of UIView and you'll get touch handling.

提交回复
热议问题