Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: hitTest for UIView underneath another UIView

I have TransparentUIView on top of RedOrGreenUIView. TransparentUIView has a UILongPressGestureRecognizer attached to it. Once user begins a long touch on it, I check for .Changed status of this LongPressGesture, and execute below hitTest:

var p:CGPoint = rec.locationInView(self.view)
var selectedView = view.hitTest(p, withEvent: nil)
if selectedView != nil {
   if selectedView == TransparentUIView {
       println("TransparentUIView is being touched")
   }
}

I get TransparentView as selectedView fine. However I need to be able to conduct a hitTest on RedOrGreenUIView at the same time, which is underneath TransparentUIView. I cant get my head around to accomplishing this. Please help.

like image 944
Kashif Avatar asked Dec 04 '22 04:12

Kashif


2 Answers

Create a custom view for your container and override the pointInside: message to return NO when the point isn't within an eligible child view, like this:

@interface PassthroughView : UIView
@end

@implementation PassthroughView
-(BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
    for (UIView *view in self.subviews) {
        if (!view.hidden && view.alpha > 0 && view.userInteractionEnabled && [view pointInside:[self convertPoint:point toView:view] withEvent:event])
            return YES;
    }
    return NO;
}
@end

swift version

class PassThroughView: UIView {

     override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool {
            for subview in subviews as [UIView] {
                if !subview.hidden && subview.alpha > 0 && subview.userInteractionEnabled && subview.pointInside(convertPoint(point, toView: subview), withEvent: event) {
                    return true
                }
            }
            return false
        }
    }
like image 80
Suraj K Thomas Avatar answered Dec 11 '22 09:12

Suraj K Thomas


Swift 4 version :

 override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        for subview in YourView.subviews as [UIView] {

            if !subview.isHidden && subview.alpha > 0 && subview.isUserInteractionEnabled && subview.point(inside:point, with: event) {
                return true
            }
        }

    return false
 }
like image 44
byJeevan Avatar answered Dec 11 '22 10:12

byJeevan