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
andtoolbarDidRemoveItem
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
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]
}
}