1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
class ViewController: NSViewController { @IBOutlet weak var xview: NSView! override func viewDidLoad() { super.viewDidLoad() xview.wantsLayer = true } //1. var isPresentingSlideshow = false @IBAction func toggle(_ sender: Any) { if(isPresentingSlideshow) { isPresentingSlideshow = false xview.layer?.backgroundColor = NSColor.green.cgColor teardownTracking() } else { isPresentingSlideshow = true xview.layer?.backgroundColor = NSColor.red.cgColor setupTracking() } } //2. var trackingArea:NSTrackingArea? func setupTracking() { let area = NSTrackingArea(rect: xview.bounds, options: [.activeAlways,.mouseEnteredAndExited,.mouseMoved,.inVisibleRect] , owner: self, userInfo: nil) xview.addTrackingArea(area) trackingArea = area } //3. func teardownTracking() { if let trackingArea = trackingArea { xview.removeTrackingArea(trackingArea) self.trackingArea = nil NSCursor.setHiddenUntilMouseMoves(false) } } //4. var cursorHideState = false override func mouseMoved(with event: NSEvent) { super.mouseMoved(with: event) if !cursorHideState { cursorHideState = true //5. DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) { [weak self] in if let _ = self?.trackingArea { NSCursor.setHiddenUntilMouseMoves(true) self?.cursorHideState = false } } } } } |
What going on here is.
- Simple toggle action to flip between playing/not-playing state and reflect that in the color state.
- Adds a
NSTrackingArea
to the view. The owner is this view controller so it will receive themouseMoved:
event. The option.mouseMoved
is required to set this up. - Removes the tracking area from the view when the slide show isn’t playing and sets
setHiddenUntilMouseMoves
to false. - The
mouseMoved:
handler - The
setHiddenUntilMouseMoves
is set true after two seconds as long as the tracking area exists and its not already waiting. Note the weak reference toself
prevents a possible retain cycle here.
This isn’t perfect as you might find that the cursor hides once after leaving your window but should get you going in the right direction.