Created
October 12, 2017 07:08
-
-
Save anonymous/d0b2d458b58a74d9ef97307f0fa9f834 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Cocoa | |
class ViewController: NSViewController { | |
@IBOutlet weak var tb: NSTableView! | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
let ctxm = NSMenu() | |
tb.menu = ctxm | |
ctxm.delegate = self | |
} | |
override var representedObject: Any? { | |
didSet { | |
} | |
} | |
} | |
final class Action:NSObject { | |
private let _action: ()->() | |
init (_ action: @escaping ()->()) { | |
self._action = action | |
super.init() | |
} | |
@objc func action () { | |
_action() | |
} | |
} | |
final class WhatEver: NSObject { | |
private let _closure: () -> () | |
init(_ closure: @escaping () -> ()) { | |
self._closure = closure | |
super.init() | |
} | |
@objc func invoke() { | |
_closure() | |
} | |
} | |
extension ViewController:NSMenuDelegate { | |
func menuWillOpen(_ menu: NSMenu) { | |
menu.removeAllItems() | |
let item2 = NSMenuItem() | |
item2.title = "Item_2" | |
let closure = WhatEver({print("xxx")}) | |
item2.target = closure | |
item2.action = #selector(closure.invoke) | |
objc_setAssociatedObject(self, String(format: "[%d]", arc4random()), closure, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) | |
menu.addItem(item2) | |
let item1 = NSMenuItem() | |
item1.title = "Item_1" | |
let action = Action({print("xxx")}) | |
item1.target = action | |
item1.action = #selector(action.action) | |
objc_setAssociatedObject(self, String(format: "[%d]", arc4random()), action, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) | |
menu.addItem(item1) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment