context menu based on NSTableViewCell

后端 未结 7 744
余生分开走
余生分开走 2021-02-03 12:16

i would like to place a context menu onto a NSTableView. this part is done. what i would liek to do is to show different menu entries based on the content of the ri

7条回答
  •  庸人自扰
    2021-02-03 12:39

    This is the easiest method for a custom/dynamic NSMenu I found, that also preserves the system look (the blue selection border). Subclass NSTableView and set your menu in menu(for:).

    The important part is to set the menu on the table view, but return the menu from its super call.

    override func menu(for event: NSEvent) -> NSMenu? {
        let point = convert(event.locationInWindow, from: nil)
        let clickedRow = self.row(at: point)
        var menuRows = selectedRowIndexes
    
        // The blue selection box should always reflect the
        // returned row indexes.
        if menuRows.isEmpty || !menuRows.contains(clickedRow) {
            menuRows = [clickedRow]
        }
    
        // Build your custom menu based on the menuRows indexes
        self.menu = <#myMenu#>
    
        return super.menu(for: event)
    }
    

提交回复
热议问题