How to add toolbar programatically in macOS

Issue #713

To setup toolbar, we need to implement NSToolbarDelegate that provides toolbar items. This delegate is responsible for many things

  • Set visible and allowed items with toolbarDefaultItemIdentifiers
  • Provide item with itemForItemIdentifier
  • Being notified with toolbarWillAddItem and toolbarDidRemoveItem
1
2
3
4
5
6
7
8
window.toolbarStyle = .unifiedCompact

let toolbar = NSToolbar(identifier: "Toolbar")
toolbar.displayMode = .iconAndLabel
toolbar.delegate = (NSApp.delegate as! AppDelegate)
toolbar.insertItem(withItemIdentifier: .add, at: 0)
toolbar.insertItem(withItemIdentifier: .settings, at: 1)
window.toolbar = toolbar
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
extension NSToolbarItem.Identifier {
static let add = NSToolbarItem.Identifier(rawValue: "Add")
static let settings = NSToolbarItem.Identifier(rawValue: "Settings")
}

extension AppDelegate: NSToolbarDelegate {
func toolbar(
_ toolbar: NSToolbar,
itemForItemIdentifier itemIdentifier: NSToolbarItem.Identifier,
willBeInsertedIntoToolbar flag: Bool
) -> NSToolbarItem? {
switch itemIdentifier {
case .add:
let item = NSToolbarItem(itemIdentifier: itemIdentifier)
item.label = "Add"
item.image = NSImage(named: NSImage.Name("add"))
let menuItem: NSMenuItem = NSMenuItem()
menuItem.submenu = nil
menuItem.title = "Add"
item.menuFormRepresentation = menuItem
item.toolTip = "Click here to add new entry"
return item
case .settings:
let item = NSToolbarItem(itemIdentifier: itemIdentifier)
item.label = "Settings"
let button = NSButton(image: NSImage(named: NSImage.Name("gear"))!, target: nil, action: nil)
button.bezelStyle = .texturedRounded
item.view = button
return item
default:
return nil
}
}

func toolbarDefaultItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] {
[.add, .settings]
}

func toolbarAllowedItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] {
[.add, .settings]
}
}

Read more

Comments