デフォルトで左のようになっているコンテクストメニューを右のようにしたい。辞書、Google で検索、カット、コピー、ペースト の部分だけは最低限残す。ちなみに Spotlight〜テキストを全角に変換 の部分は自動挿入されるサービスメニューで、これは NSMenu のプロパティで削除できる。
extension TextDelegate: NSTextDelegate {
// コンテクストメニューを返すためのデリゲートメソッド。標準のメニューは引数で渡される
func textView(view: NSTextView, menu: NSMenu, forEvent event: NSEvent, atIndex charIndex: Int) -> NSMenu? {
let newMenu = NSMenu(title: "")
newMenu.allowsContextMenuPlugIns = false // サービスメニューを挿入したくない場合は false
var specialItems = 0
for item in menu.itemArray {
// 辞書で表示、Google で検索
if item.action.description == "_searchWithGoogleFromMenu:" ||
item.action.description == "_lookUpDefiniteRangeInDictionaryFromMenu:" {
newMenu.addItem(item.copy() as! NSMenuItem)
specialItems += 1
}
// 区切り線を入れる
if specialItems == 2 {
newMenu.addItem(NSMenuItem.separatorItem())
specialItems += 1
}
// カット、コピー、ペースト
if item.action.description == "cut:" ||
item.action.description == "copy:" ||
item.action.description == "paste:" {
newMenu.addItem(item.copy() as! NSMenuItem)
}
// デバッグ用
//print("\(item.target), \(item.action.description), \(item.title)")
}
return newMenu
}
}
あとはよしなに好きなメニュー項目を挿入すれば良い。