How get associated view of context menu?

I have a menu that is set as context menu of several NSTableViews, like below:

        let appDelegate = NSApp.delegate as! AppDelegate
        self.localeTable.menu = appDelegate.selectMenu
        self.fileTable.menu = appDelegate.selectMenu
        self.stringsTable.menu = appDelegate.selectMenu

Now my problem is that in the menu item's event handler, how do I know which NSTableView is current event for?

@IBAction func selectMenuItem_select(_ sender: Any) 
}

Replies

sender should be an NSMenuItem.


You could probably set a tag :

let localMenuTag = 1
let fileTableMenuTag = 2
let stringsTableMenuTag = 3


then, when you define

        self.localeTable.menu = appDelegate.selectMenu

set the tag for all its menuItems to localMenuTag


Similarly for the other menus


Then in IBAction

@IBAction func selectMenuItem_select(_ sender: Any) {
     guard let menuItem = sender as? NSMenuItem else { return }
     let tag = menuItem.tag     // Now you know which table you come from
}

Maybe I did not state my problem clear enough. The three NSTableViews shared exactly one same menu. In the event handler for one menuitem, I do not know which table view to act upon. BTW, I did set different tag values for each menuitem before I asked this question.

Any more ideas?

Ideally, that info should be conveyed by the sender.

So, you could change the tag values of each menuItem of appDelegate.selectMenu,when you right click in the menu, to the same value

  1. localMenuTag
  2. fileTableMenuTag
  3. stringsTableMenuTag

depending which table you call from.

Note that all menuItems would have the same tag (that indicates which tableView they are called from)


Another way (not very clean), would be to test in IBAction who is the first responder ; that should tell you the tableView (if you call from one of the table views)


Or you could create a global that is set to the tableView when you contectClick in it

and use this var in IBAction.

Thanks for you replies, but unfortunately, I did not understand your solution.

What don't you understand ?


What I propose:


in the func that deals with the control-click in the cell (for example for localeTable), to call context menu:

- start by adjusting the tags in all menu items of appDelegate.selectMenu

- set the tag value to ALL menuItems of selectMenu to localMenuTag

- set the menu : self.localeTable.menu = appDelegate.selectMenu


Doing son when you call

IBAction func selectMenuItem_select(_ sender: Any)


sender (as MenuItem) tag (localMenuTag) will let you know that is was called from localeTable

Is this a contextual menu for the NSTableView itself or for a cell/row in the NSTableView?


Because in the second case, the clickedRow property of the corresponding table view will probably be the only one not being -1.


This is not a pretty solution though.