我正在尝试将项目添加到xcode中的现有上下文菜单中。到目前为止,我已经设法将一个项目添加到与特定的一个相对的所有上下文菜单中。我使用“NSMenuDidBeginTrackingNotification.object”来引用菜单对象,但不确定这是正确的方法。代码如下。任何想法??
非常感谢!
import AppKit
var sharedPlugin: plugin?
class plugin: NSObject {
var bundle: NSBundle
lazy var center = NSNotificationCenter.defaultCenter()
// object holding all notifications:
var notificationSet = NSMutableSet();
class func pluginDidLoad(bundle: NSBundle) {
let appName = NSBundle.mainBundle().infoDictionary?["CFBundleName"] as? NSString
if appName == "Xcode" {
sharedPlugin = plugin(bundle: bundle)
}
}
init(bundle: NSBundle) {
self.bundle = bundle
self.notificationSet = NSMutableSet()
super.init()
// see name: "NSMenuDidBeginTrackingNotification":
center.addObserver(self, selector: #selector(self.createMenuItems), name:"NSMenuDidBeginTrackingNotification", object: nil)
}
deinit {
removeObserver()
}
func removeObserver() {
center.removeObserver(self)
}
func createMenuItems(notification: NSNotification) {
// checking what pops up the context menu when right clicking the console:
if (!(self.notificationSet).containsObject(notification.name)) {
print(notification.name)
print(notification.object?.className)
self.notificationSet.addObject(notification.name);
let menu = notification.object;
//creating menu item 'testing' :
let menuItem = NSMenuItem(title:"testing", action:#selector(self.doMenuAction), keyEquivalent:"");
menuItem.target = self
//adding item to context menu:
menu!.addItem(menuItem)
let actionMenuItem = NSMenuItem(title:"Do Action", action:#selector(self.doMenuAction), keyEquivalent:"")
actionMenuItem.target = self
}
}
func doMenuAction() {
print("hi")
self.notificationSet.removeAllObjects()
}
}