iosswiftuiuitouchapple-pencil

Is there any ways to handle and/or distinguish Apple Pencil and direct touches in SwiftUI?


I am wondering if there is a way to handle Apple Pencil events in SwiftUI? For example if you like to handle direct touches, and Apple Pencil differently, say direct touch to scroll, but Apple Pencil to draw lines.

There is a similar type of question like this.

How to Handle screen touch events with SwiftUI?

But DragGesture, for example, there seems to be no accessor to UITouch.TouchType like attributes to distinguish direct, indirect or pencil.

If there is no way, or giving me some hybrid techniques with UIView, then oh well...

Thanks,


Solution

  • I think the best way to do this is to create a custom UIGestureRecognizer. This way you can override touchesBegan, touchesMoved and so on and get access to the UITouch object that will include UITouch.TouchType.

    See Apple's Sample Code here, specifically the StrokeGestureRecognizerclass.