swift 在hitTest()或pointInside()中获取触摸类型

rsl1atfo  于 2022-12-02  发布在  Swift
关注(0)|答案(1)|浏览(144)

我通过在顶部创建一个透明视图并覆盖hitTest()来实现passThroughView。
passThroughView应使用Apple Pencil的触摸,如果触摸类型不是来自Pencil,则它会将触摸传递到下面的视图。
问题是:

  • hitTest中的参数“event”不包含触摸,因此无法在hitTest中检查触摸类型
  • 我可以从touchesBegan获取触摸并检查触摸类型,但只有在hitTest返回true后才调用它
  • 我子类化了UIWindow并覆盖了sendEvent(),但这个函数也在hitTest之后调用(我不知道为什么)
class WindowAbleToKnowTouchTypes: UIWindow {
    override func sendEvent(_ event: UIEvent) {
        if event.type == .touches {
            // This get called after Hittest
            if event.allTouches!.first!.type == .pencil {
                print("This touch is from Apple Pencil")
            }
        }
        super.sendEvent(event)
    }
}

是否有任何方法可以检查touchType来决定传递或使用触摸?

fdbelqdn

fdbelqdn1#

我最终使用了一种不同的方法,它可能对许多情况都有用:如果在hitTest()中无法获取touchType,我仍然可以使用GestureRecognize获取touchType:

class CustomGestureRecognizer : ImmediatePanGesture {
    var beganTouch : UITouch!
    var movedTouch : UITouch!
    var endedTouch : UITouch!

    override func shouldReceive(_ event: UIEvent) -> Bool {
        // You can check for touchType here and decide if this gesture should receice the touch or not
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
        // Save touch for later use
        if let firstTouch = touches.first {
            beganTouch = firstTouch
        }
        super.touchesBegan(touches, with: event)
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent) {
        // Save touch for later use
        if let touch = touches.first {
            movedTouch = touch
        }
    
        super.touchesMoved(touches, with: event)
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent) {
        // Save touch for later use
        if let touch = touches.first {
            endedTouch = touch
        }
    
        super.touchesEnded(touches, with: event)
    }
}

在gestureRecognizer的目标函数中,可以通过以下方式获取UITouch:

let beganTouch = customGesture.beganTouch
let touchType = beganTouch.touchType

相关问题