context menu based on NSTableViewCell

后端 未结 7 736
余生分开走
余生分开走 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:40

    Warren Burton's answer is spot on. For those working in Swift, the following example fragment might save you the work of translating from Objective C. In my case I was adding the contextual menu to cells in an NSOutlineView rather than an NSTableView. In this example the menu constructor looks at the item and provides different options depending on item type and state. The delegate (set in IB) is a ViewController that manages an NSOutlineView.

     func menuNeedsUpdate(menu: NSMenu) {
        // get the row/column from the NSTableView (or a subclasse, as here, an NSOutlineView)
        let row = outlineView.clickedRow
        let col = outlineView.clickedColumn
        if row < 0 || col < 0 {
            return
        }
        let newItems = constructMenuForRow(row, andColumn: col)
        menu.removeAllItems()
        for item in newItems {
            menu.addItem(item)
            // target this object for handling the actions
            item.target = self
        }
    }
    
    func constructMenuForRow(row: Int, andColumn column: Int) -> [NSMenuItem]
    {
        let menuItemSeparator = NSMenuItem.separatorItem()
        let menuItemRefresh = NSMenuItem(title: "Refresh", action: #selector(refresh), keyEquivalent: "")
        let item = outlineView.itemAtRow(row)
        if let block = item as? Block {
            let menuItem1 = NSMenuItem(title: "Delete \(block.name)", action: #selector(deleteBlock), keyEquivalent: "")
            let menuItem2 = NSMenuItem(title: "New List", action: #selector(addList), keyEquivalent: "")
            return [menuItem1, menuItem2, menuItemSeparator, menuItemRefresh]
        }
        if let field = item as? Field {
            let menuItem1 = NSMenuItem(title: "Delete \(field.name)", action: #selector(deleteField), keyEquivalent: "")
            let menuItem2 = NSMenuItem(title: "New Field", action: #selector(addField), keyEquivalent: "")
            return [menuItem1, menuItem2, menuItemSeparator, menuItemRefresh]
        }
        return [NSMenuItem]()
    }
    

提交回复
热议问题