Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read dictionary from NSEvent userData

I have created an NSTrackingArea and I am passing a Dictionary in the userInfo argument.

let trackingData = ["section": 1, "sectionRow": 12, "done": false]
let trackingArea = NSTrackingArea(
                            rect: cellView.bounds,
                            options: [NSTrackingAreaOptions.MouseEnteredAndExited, NSTrackingAreaOptions.ActiveAlways],
                            owner: self,
                            userInfo: trackingData as? [String : AnyObject])
cellView.addTrackingArea(trackingArea)

This event is successfully received here;

override func mouseEntered(event: NSEvent) {
        print("Mouse Entered \(event.userData)")
    }

How can I read the values for section etc from userData?

like image 622
Shakeeb Ahmad Avatar asked Sep 21 '26 17:09

Shakeeb Ahmad


1 Answers

Using your syntax

if let userData = event.trackingArea?.userInfo as? [String : AnyObject] {
  let section = userData["section"] as! Int
}

But if you pass the done key as Int with value 0 or 1 rather than Bool, you don't need cast the values of the dictionary because it's distinct [String:Int]

let trackingArea = NSTrackingArea(rect: ... , userInfo: trackingData)

and

if let userData = event.trackingArea?.userInfo as? [String : Int] {
  let section = event.userData["section"]!
}  

The optional bindings are for safety, if there are more events to receive and track.

like image 106
vadian Avatar answered Sep 23 '26 11:09

vadian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!