Skip to content

Instantly share code, notes, and snippets.

Created October 12, 2017 07:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/d0b2d458b58a74d9ef97307f0fa9f834 to your computer and use it in GitHub Desktop.
Save anonymous/d0b2d458b58a74d9ef97307f0fa9f834 to your computer and use it in GitHub Desktop.
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