Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add NSMenu Programmatically?

I didn't use storyboard and xib, just used only code. I would like to add "Edit" Menu Programmatically. My Questions are

1) How to show "Edit" Menu / What codes need to input at comment Question 1)?

2) There are any actions provided from swift like copy & paste?

class TestManager: NSObject {

// ....
    override init() {
        let editMenuItems = [
            NSMenuItem(title: "Cut", action: nil(/* Question 2) */), keyEquivalent: ""),
            NSMenuItem(title: "Copy", action: nil, keyEquivalent: ""),
            NSMenuItem(title: "Paste", action: nil, keyEquivalent: ""),
        ]

        for editMenuItem in editMenuItems {
            self.editMenu.addItem(editMenuItem)
        }

        // Qustion 1) .. show "Edit" Menu
    }
}
like image 424
Astin Avatar asked Feb 28 '15 12:02

Astin


1 Answers

You don't show where self.editMenu comes from.

In any case, you need to obtain the mainMenu from the NSApplication instance and add a menu item to that which has your menu as its submenu. So, something like:

var editMenuItem = NSMenuItem()
editMenuItem.title = "Edit"
var mainMenu = NSMenu()
mainMenu.addItem(editMenuItem)
mainMenu.setSubmenu(self.editMenu, forItem:editMenuItem)
NSApplication.sharedApplication().mainMenu = mainMenu

I don't work in Swift, so there are probably some mistakes in there.

As to what action selector to use for Edit menu items, the easiest thing for you to do is to create a main menu NIB just to examine it. Look at the action selectors used for the menu items of the ready-made Edit menu. You'll find that the Copy item uses the copy: selector, for example. That can be represented in Swift as just a string, "copy:".

like image 68
Ken Thomases Avatar answered Sep 30 '22 11:09

Ken Thomases