How to detect touch over a UIView when touched ove

2019-07-26 13:17发布

问题:

I'm using (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event, and (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event to handle some dragging on a UIView. This UIView however have some UIButtons as subviews of the UIView and when the user touches over a UIButton (which are also over the UIView) the touches methods aren't called.

I need the touch methods in the UIView to be called at all times and still have the UIButtons working, how can I achieve this?

回答1:

OK, no problem, I solved my question already.

The way is to override the touch methods in the buttons also like this:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    touchMoved = NO;
    [[self superview] touchesBegan:touches withEvent:event];
    [super touchesBegan:touches withEvent:event];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    touchMoved = YES;
    [[self superview] touchesMoved:touches withEvent:event];
    [super touchesMoved:touches withEvent:event];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    if (!touchMoved) [super touchesEnded:touches withEvent:event];
}

The touchMoved variable is meant to track if it was a direct touch to the button or if the touch was meant to drag the superview. As I'm using UIControlEventTouchUpInside then it works fine if I disable the touchesEnded when it has tracked a touch movement.