Allow UIScrollView and its subviews to both respond to a touch

前端 未结 5 565
轮回少年
轮回少年 2020-12-04 16:11

I want both my UIScrollView and its subviews to receive all touch events inside the subview. Each can respond in its own way.

Alternatively, if tap gestures were fo

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-04 16:36

    I don't know if this can help you, but I had a similar problem, where I wanted the scrollview to handle double-tap, but forward single tap to subviews. Here is the code used in a CustomScrollView

    - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    
        UITouch* touch = [touches anyObject];
        // Coordinates
        CGPoint point = [touch locationInView:[self.subviews objectAtIndex:0]];
    
        // One tap, forward
        if(touch.tapCount == 1){
            // for each subview
            for(UIView* overlayView in self.subviews){
                // Forward to my subclasss only
                if([overlayView isKindOfClass:[OverlayView class]]){
                    // translate coordinate
                    CGPoint newPoint = [touch locationInView:overlayView];
                    //NSLog(@"%@",NSStringFromCGPoint(newPoint));
    
                    BOOL isInside = [overlayView pointInside:newPoint withEvent:event];
                    //if subview is hit
                    if(isInside){
                        Forwarding
                        [overlayView touchesEnded:touches withEvent:event];
                        break;
                    }
                }
            }
    
        }
        // double tap : handle zoom
        else if(touch.tapCount == 2){
    
            if(self.zoomScale == self.maximumZoomScale){
                [self setZoomScale:[self minimumZoomScale] animated:YES];
            } else {
                CGRect zoomRect = [self zoomRectForScrollView:self withScale:self.maximumZoomScale withCenter:point];            
    
                [self zoomToRect:zoomRect animated:YES];
            }
    
            [self setNeedsDisplay];
    
        }
    }
    

    Of course, the effective code should be changed, but at this point you should have all the informations you need to decide if you have to forward the event. You might need to implement this in another method as touchesMoved:withEvent:.

    Hope this can help.

提交回复
热议问题