美文网首页MacOS开发 技术集锦
swift 实现 macOS NSTableView 右键菜单

swift 实现 macOS NSTableView 右键菜单

作者: 搞好关系 | 来源:发表于2018-10-06 23:57 被阅读31次

    定义一个protocol

    @objc protocol ContextMenu {
        @objc func tableView(_ tableView: NSTableView, menuForRows rows:IndexSet)->NSMenu?
        @objc func tableView(_ tableView: NSTableView, clickForRow row: Int) -> Void
    }
    

    extension tableview重写鼠标事件

    extension NSTableView {
        open override func menu(for event: NSEvent) -> NSMenu? {
            let location = self.convert(event.locationInWindow, from: nil)
            let row = self.row(at: location)
            if row >= 0 && event.type == .rightMouseDown {
                
                var selected = self.selectedRowIndexes
                if  false ==  selected.contains(row) {
                    selected = IndexSet.init(integer: row)
                    self.selectRowIndexes(selected, byExtendingSelection: false)
                }
                if  let dele:ContextMenu = (self.delegate as? ContextMenu)  {
                    return   dele.tableView(self, menuForRows: selected)
                }else{
                    return super.menu(for: event)
                }
            }
            
            
            return super.menu(for: event)
        }
        open override func mouseDown(with event: NSEvent) {
            let location = self.convert(event.locationInWindow, from: nil)
            let row = self.row(at: location)
            if row >= 0 && event.type == .rightMouseDown {
                
                var selected = self.selectedRowIndexes
                if  false ==  selected.contains(row) {
                    selected = IndexSet.init(integer: row)
                    self.selectRowIndexes(selected, byExtendingSelection: false)
                }
                if  let dele:ContextMenu = (self.delegate as? ContextMenu)  {
                    dele.tableView(self, clickForRow: row)
                }
            }
            return super.mouseDown(with: event)
        }
        open override func mouseEntered(with event: NSEvent) {
            var btInfo:BTInfo = BTInfo()
        }
        open override func mouseExited(with event: NSEvent) {
            
        }
    }
    
    

    使用

    extension BTViewController: ContextMenu{
        @objc func tableView(_ tableView: NSTableView, menuForRows rows:IndexSet)->NSMenu?{
            let bt: BT = self.bts![self.btTableView.selectedRow]
            
          
            return self.menus(forTables: tableView, item: bt)
        }
        @objc func tableView(_ tableView: NSTableView, clickForRow row: Int) -> Void {
            
        }
    }
    
    

    相关文章

      网友评论

        本文标题:swift 实现 macOS NSTableView 右键菜单

        本文链接:https://www.haomeiwen.com/subject/zqykaftx.html