'listening for multitouch events in OS X using the touchesBegan and touchesMoved event handlers
I am trying to record touches and finger movements that users perform on a 2018 MacBook Trackpad.
When I try to test the API and print to console when the user touches the Trackpad, I see no output.
How do I listen for touch events and get data from them?
I referred to the handling Trackpad events documentation. The handling multitouch events section of the page says:
A view by default does not accept touch events. To handle touch events, your custom view must first call the NSView method
setAcceptsTouchEvents:
with an argument of YES.
However, the setAcceptsTouchEvents documentation says the method is deprecated.
When I try just printing a log on detecting a touch to test if the API is working, I do not see any console output. here is my code:
import Cocoa
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
override func touchesBegan(with event: NSEvent) {
print("touched!");
}
}
how do I get the console statement to print something?
Solution 1:[1]
I was playing around with this and here is what I figured out.
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the //view.
//view.acceptsTouchEvents = true; //deprecated but works.deprecated
view.allowedTouchTypes = [NSTouch.TouchTypeMask.direct, NSTouch.TouchTypeMask.indirect];
}
and then, you can override the functions when touches are in different phases as explained in the question.
Solution 2:[2]
Note that to do the "allowedTouchTypes" massage in a subclass it is like this:
import Cocoa
class UnView: NSView{
override var allowedTouchTypes: NSTouch.TouchTypeMask {
get { return [] } .. as you wish
set { }
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | pkamb |
Solution 2 | Fattie |