ios touch location without uigesturerecognizer

91 Views Asked by At

How to get touch location on uiwindow or uiview without uigesturerecognizer, purpose is getting touch location in extremely low latency as dispatcher can delay touch firing events

2

There are 2 best solutions below

3
On

You need to subclass UIView and override the UIResponder (superclass of UIView) method touchesBegan(_:with:). See the docs for the method here.

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        // Get the touch location in THIS VIEW's coordinate system:
        let locationInThisView = touch.location(in: self)

        // Get the touch location in the WINDOW's coordinate system
        let locationInWindow = touch.location(in: nil)
    }
}

Also, make sure your view has the property isUserInteractionEnabled set to true.

1
On

Override the below method in your UIView subclass.

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let point =  touches.first?.location(in: self)
    print("location: ", point ?? CGPoint.zero)
}