Chapters

Hide chapters

Catalyst by Tutorials

First Edition · iOS 13 · Swift 5.1 · Xcode 11

Before You Begin

Section 0: 3 chapters
Show chapters Hide chapters

11. Barista Training: Toolbar
Written by Andy Pereira

Heads up... You're reading this book for free, with parts of this chapter shown beyond this point as scrambled text.

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.

#import <Foundation/Foundation.h>
#import <UIKit/NSToolbar+UIKitAdditions.h>
#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 [.addEntry, .deleteEntry, .shareEntry, .flexibleSpace]
}
func toolbarDefaultItemIdentifiers(_ toolbar: NSToolbar)
  -> [NSToolbarItem.Identifier] {
    return [.addEntry, .flexibleSpace, .shareEntry]
}
// 1. 
func toolbar(_ toolbar: NSToolbar,
  itemForItemIdentifier itemIdentifier: 
  NSToolbarItem.Identifier,
  willBeInsertedIntoToolbar flag: Bool) -> NSToolbarItem? {
    var item: NSToolbarItem? = nil
    return item
}

// 2. 
@objc private func addEntry() {
}
  
@objc private func deleteEntry() {
}

@objc private func shareEntry(_ sender: UIBarButtonItem) {
}
private func toolbarItem(
  itemIdentifier: NSToolbarItem.Identifier,
  barButtonItem: UIBarButtonItem,
  toolTip: String? = nil, label: String?) -> NSToolbarItem {
    // 1.
    let item = NSToolbarItem(itemIdentifier: itemIdentifier,
      barButtonItem: barButtonItem)
    // 2. 
    item.isBordered = true
    // 3.
    item.toolTip = toolTip
    if let label = label {
      // 4.
      item.label = label
    }
    return item
}
func toolbar(_ toolbar: NSToolbar, 
  itemForItemIdentifier itemIdentifier: 
  NSToolbarItem.Identifier, 
  willBeInsertedIntoToolbar flag: Bool) -> NSToolbarItem? {
  
  var item: NSToolbarItem? = nil
  if itemIdentifier == .addEntry {
    let barButtonItem =
      UIBarButtonItem(barButtonSystemItem: .add,
                      target: self,
                      action: #selector(addEntry))
    item = toolbarItem(itemIdentifier: .addEntry,
                       barButtonItem: barButtonItem,
                       toolTip: "Add Entry",
                       label: "Add")
    item?.target = self
    item?.action = #selector(addEntry)
  } else if itemIdentifier == .deleteEntry {
    let barButtonItem =
      UIBarButtonItem(barButtonSystemItem: .trash,
                      target: self,
                      action: #selector(deleteEntry))
    item = toolbarItem(itemIdentifier: .deleteEntry,
                       barButtonItem: barButtonItem,
                       toolTip: "Delete Entry",
                       label: "Delete")
    item?.target = self
    item?.action = #selector(deleteEntry)
  } else if itemIdentifier == .shareEntry {
    let barButtonItem =
      UIBarButtonItem(barButtonSystemItem: .action,
                      target: self,
                      action: #selector(shareEntry(_:)))
    item = toolbarItem(itemIdentifier: .shareEntry,
                       barButtonItem: barButtonItem,
                       toolTip: "Share Entry",
                       label: "Share")
  }
  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

item.paletteLabel = label
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, add this implementation to addEntry():

DataService.shared.addEntry(Entry())

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)
guard let splitViewController =
  window?.rootViewController as? UISplitViewController,
  let navigationController =
  splitViewController.viewControllers.last
    as? UINavigationController,
  let entryTableViewController =
  navigationController.topViewController
    as? EntryTableViewController else {
    return
}
entryTableViewController.share(sender)

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 default 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.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.

You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a Kodeco Personal Plan.

Unlock now