2

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?

Shakeeb Ahmad
  • 2,010
  • 1
  • 25
  • 30

1 Answers1

4

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.

vadian
  • 274,689
  • 30
  • 353
  • 361
  • This is exactly how I was trying to do it. But it gives me this error: Cannot convert value of type 'String' to expected argument type 'Int' – Shakeeb Ahmad Jan 13 '16 at 14:59
  • `NSTrackingArea` passes the `userInfo` dictionary as `[NSObject : AnyObject]?` therefore you have to cast the dictionary anyway to something more specific. And you have to read also explicitly the tracking area. I updated the answer. – vadian Jan 13 '16 at 15:05
  • This just crashes on runtime. EXC_BAD_INSTRUCTION. xCode gives warning Cast from 'UnsafeMutablePointer' to unrelated type. – Shakeeb Ahmad Jan 13 '16 at 15:12