7

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,

Kaz Yoshikawa
  • 1,577
  • 1
  • 18
  • 26

4 Answers4

1

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.

user3615737
  • 104
  • 4
0
extension MTKView{
    public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        print(touches.first?.type.rawValue)
    }
}
David Buck
  • 3,752
  • 35
  • 31
  • 35
  • Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes. – Mark Rotteveel Aug 07 '20 at 06:55
0

Here's the hybrid techniques you mentioned. It's super simple and powerful. You can wrap a custom UIViewController handling touchEvents, and use it inside SwiftUI. All you need to do is creating a struct that conforms to UIViewControllerRepresentable.

https://developer.apple.com/documentation/swiftui/uiviewcontrollerrepresentable

Desmond
  • 767
  • 1
  • 6
  • 18
0

If you need to access UIKit gesture with SwiftUI. This thread can help you to get started :

Wrapping UIView around the SwiftUI, that the touch and drawn coordinate is now mis-aligned?

You will use UIViewControllerRepresentable

CharlieWhite
  • 133
  • 1
  • 12