Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make touch events pass through a UIView (similar to pointer-events:none in CSS)?

In CSS, pointer-events:none; allows click events to pass through an element. I'm curious if there is anything similar that I can do in Objective-C on iOS for UIViews.

Here's a jsfiddle to an example of pointer-events: none.

Could I somehow achieve the same behavior for a UIView by overriding hitTest:withEvent:? Or maybe there is another way to do this?

Thanks for any help.

like image 267
aleclarson Avatar asked Dec 06 '22 03:12

aleclarson


1 Answers

Here's a handy implementation in line with your initial intuition:

#import "TouchTransparentView.h"

@implementation TouchTransparentView

-(id)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    id hitView = [super hitTest:point withEvent:event];
    if (hitView == self) {
        return nil;
    } else {
        return hitView;
    }
}

@end

Swift version, with a @IB upgrade

import UIKit

@IBDesignable
class PassthroughTouchView: UIView {

    @IBInspectable var passthroughTouchEvents : Bool = false

    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        let hitView = super.hitTest(point, with: event)
        if hitView == self && passthroughTouchEvents == true {
            return nil;
        } else {
            return hitView;
        }
    }
}

set view class in IB to ours toggle now accessible in IB

like image 111
tooluser Avatar answered Dec 11 '22 10:12

tooluser