LoginSignup
5
2

More than 5 years have passed since last update.

NSTextView のコンテクストメニューをハックする

Posted at

デフォルトで左のようになっているコンテクストメニューを右のようにしたい。辞書、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
    }
}

あとはよしなに好きなメニュー項目を挿入すれば良い。

5
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2