11
Barista Training: Toolbar
Written by Andy Pereira
Toolbars are an essential part of macOS applications. Without a doubt, NSToolbar is used so ubiquitously across so many apps that most users may overlook its presence. Because of this, it’s essential to understand what you get when you use a toolbar and how toolbars behave. By adopting NSToolbar in your app, you have access to almost two decades worth of work from the smart developers and designers at Apple.
Getting started
Open the starter project for this chapter. Select My Mac for the active scheme, and Build and run. At the moment, this project has a split view controller and can handle multiple windows:
Adding the toolbar
NSToolbar is a macOS-specific control. In the past, you probably had to use macros or targets to ensure frameworks did not get imported into unsupported builds. With Catalyst, you’ll need to be able to integrate your macOS, iOS and iPadOS code more seamlessly.
#if targetEnvironment(macCatalyst)
// 1
if let scene = scene as? UIWindowScene,
let titlebar = scene.titlebar {
// 2
let toolbar = NSToolbar(identifier: "Toolbar")
// 3
titlebar.toolbar = toolbar
}
#endif
#if targetEnvironment(macCatalyst)
navigationController?.navigationBar.isHidden = true
#endif
Adding buttons
In its current state, the toolbar is providing no functionality to the app. To start adding functionality, you’ll be adding a few buttons.
toolbar.delegate = self
extension NSToolbarItem.Identifier {
static let addEntry =
NSToolbarItem.Identifier(rawValue: "AddEntry")
static let deleteEntry =
NSToolbarItem.Identifier(rawValue: "DeleteEntry")
static let shareEntry =
NSToolbarItem.Identifier(rawValue: "ShareEntry")
}
extension SceneDelegate: NSToolbarDelegate {
}
func toolbarAllowedItemIdentifiers(_ toolbar: NSToolbar)
-> [NSToolbarItem.Identifier] {
return [.toggleSidebar, .addEntry, .deleteEntry, .shareEntry, .flexibleSpace]
}
func toolbarDefaultItemIdentifiers(_ toolbar: NSToolbar)
-> [NSToolbarItem.Identifier] {
return [.toggleSidebar, .addEntry, .shareEntry]
}
// 1.
func toolbar(_ toolbar: NSToolbar,
itemForItemIdentifier itemIdentifier:
NSToolbarItem.Identifier,
willBeInsertedIntoToolbar flag: Bool) -> NSToolbarItem? {
var item: NSToolbarItem?
return item
}
// 2.
@objc private func addEntry() {
}
@objc private func deleteEntry() {
}
#if targetEnvironment(macCatalyst)
private let shareItem =
NSSharingServicePickerToolbarItem(itemIdentifier: .shareEntry)
#endif
func toolbar(_ toolbar: NSToolbar,
itemForItemIdentifier itemIdentifier:
NSToolbarItem.Identifier,
willBeInsertedIntoToolbar flag: Bool) -> NSToolbarItem? {
var item: NSToolbarItem?
switch itemIdentifier {
case .addEntry:
item = NSToolbarItem(itemIdentifier: .addEntry)
item?.image = UIImage(systemName: "plus")
item?.label = "Add"
item?.toolTip = "Add Entry"
item?.target = self
item?.action = #selector(addEntry)
case .deleteEntry:
item = NSToolbarItem(itemIdentifier: .deleteEntry)
item?.image = UIImage(systemName: "trash")
item?.label = "Delete"
item?.toolTip = "Delete Entry"
item?.target = self
item?.action = #selector(deleteEntry)
case .shareEntry:
return shareItem
case .toggleSidebar:
item = NSToolbarItem(itemIdentifier: itemIdentifier)
default:
item = nil
}
return item
}
Customizing the toolbar
Toolbars don’t always have to contain a fixed set of buttons. Above, you provided a delete button without giving the user a way to see it. You can enable your toolbar to be customized by the user, and save its state between launches.
toolbar.allowsUserCustomization = true
toolbar.autosavesConfiguration = true
titlebar.titleVisibility = .hidden
Responding to actions
The last thing you need to do is respond to actions in the toolbar. To add items to the list, replace the empty implementation of addEntry()
with the following:
@objc private func addEntry() {
guard
let splitViewController
= window?.rootViewController
as? UISplitViewController,
let navigationController
= splitViewController.viewControllers.first
as? UINavigationController,
let mainTableViewController
= navigationController.topViewController
as? MainTableViewController else {
return
}
DataService.shared.addEntry(Entry())
let index = DataService.shared.allEntries.count - 1
mainTableViewController.selectEntryAtIndex(index)
}
guard let splitViewController =
window?.rootViewController as? UISplitViewController,
let navigationController =
splitViewController.viewControllers.first
as? UINavigationController,
let mainTableViewController =
navigationController.topViewController
as? MainTableViewController,
let secondaryViewController =
splitViewController.viewControllers.last
as? UINavigationController,
let entryTableViewController =
secondaryViewController.topViewController
as? EntryTableViewController,
let entry = entryTableViewController.entry,
let index = DataService.shared.allEntries
.firstIndex(of: entry) else { return }
DataService.shared.removeEntry(atIndex: index)
mainTableViewController.selectEntryAtIndex(index)
Sharing
For the final toolbar item, Share, you’ll need to do a few more steps. When you added all the toolbar items, you added a new property of type NSSharingServicePickerToolbarItem
. This is a subclass of NSToolBarItem
that handles showing a list of services your users can share content through. To get this working takes a few steps.
import Combine
private var activityItemsConfigurationSubscriber: AnyCancellable?
activityItemsConfigurationSubscriber
= NotificationCenter.default
.publisher(for: .ActivityItemsConfigurationDidChange)
.receive(on: RunLoop.main)
.map({
$0.userInfo?[NotificationKey.activityItemsConfiguration]
as? UIActivityItemsConfiguration
})
.assign(to: \.activityItemsConfiguration,
on: shareItem)
extension EntryTableViewController {
private func configureActivityItems() {
let configuration
= UIActivityItemsConfiguration(objects: [])
// 1.
configuration.metadataProvider = { key in
// 2.
guard let shareText
= self.shareText else { return nil }
switch key {
// 3.
case .title, .messageBody:
return shareText
default:
return nil
}
}
// 4.
NotificationCenter
.default
.post(name: .ActivityItemsConfigurationDidChange,
object: self,
userInfo: [NotificationKey
.activityItemsConfiguration: configuration])
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
configureActivityItems()
}
func textViewDidChange(_ textView: UITextView) {
validateState()
configureActivityItems()
}
Key points
- Use Mac style toolbars, not iOS navigation bars in macOS apps.
- Toolbars are for the entire window, not just the specific view controller presented to the user.
- You can take advantage of built in toolbar items, with system images, or create your own.
- Users are used to customizing toolbars in many apps. Ensure you provide this capability, as it makes sense.
Where to go from here?
This chapter showed you how quick it is to implement a macOS-centric design in a way that was never so easy. While knowing how to implement your own toolbar items is important, don’t forget there are several other system-provided toolbar items provided that you can put to use as well.