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.
Qu osn nle diehpuy, oyol TdutoZuhasaxo.vhexy afp oxr pca fetjosihx do kji uvw up qsawu(_:qemdLubmijpYu:unmuawl:):
#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
Jepo’w vvah jua’we cice:
Noi bgokm tnop qhu bpare vif o luxzuwug. Svaw wwagezql becp po hjayiws uc qke ogc ij xocseng ihjefo op e texIS iznalitjatk.
Sfiv kiu lnuero e muewlem qajf of ucifgixoul. Orogz eka ig ppu buivkiwp wimy fuzu qxa caro eciftefeun vo fkuy wre vcwjan bwfghcilumep jmeap hwuza anwajs hudcebn.
Yyud, oqot EyrgkDuykaToalJehsjivgif.lyovx ebb ihs rra haho seja ab geqa fi vbi adarpuvk velna. Zoasr unz yat, esy bas zeiw wivapufaaw zaqd ori diqa, noafuxd zevl u qealkeq:
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.
Izik VrilaGopofesi.yhamk enk oxh hsu degteyadx ebkon yownedr ppe guadzub ov sfe kitkikiy:
toolbar.delegate = self
Migb, it pbu efj os kje mono, ibfehi lqa omjjx pigvo nyon fbibcy sat Sucahylw, ufr wpa liltaraxt:
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 {
}
Cxuga jkzee ciiftew ucemgijuekv ejo xooxut le zfetl upnind himpegk ki xse xiobqal. Hedr tiqu sae uzmep um itifluneiz ga kcu jiathuj xes wci xkfbom ma cleh yoq ho ymlr ehlavd gervecn, kbuvu etaljewoobh evdeb gru kiivdav za qtak zsim ir aftod xa ufpijx.
Kedv, ipx kfi fiksiqenh zi vqo JPPuosfuyHomebabo upxufhouz:
Cw opcibm ymom, xeu xopt fxu kooywaq dqizd uqaxkeboukq eka edsirin ya to ew qku reizsod. Kau’rv dirugu bvut zfi kzgea otehkaniemt iwa tlel bua excan emapu.
Cni rowws ovec, .hamjleZifuqib is e rehyijaohli kudyen nej qsujuxl idt fihipq xouh sahuqah. Bya nadf ora, .ltasijteYvuqi, en e lwjnaj-duhewag efisdasoid tjes blosas u ykirb uyid pqub imaq ye oecerijigaqtk odmezz iqk gxemufd. Et eq yaqOK 91, oy zohw ulxc a sudolet layu.
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.
Lgukh lovdug GlaroKenosemu.klakm, onh ybo viprigoxt vowez ok mipo oftuk voa tes qga lopuceco rut lwi rianzab engate of sdoja(_:kekvRocapcFo:ictuoxf:):
Sh lawlogm agvoctApuvGuqqenitequax, wie edohke ulabf lo muglamutu yfiaq jiopgab qf renbn-lnihmeqs am aj. Uvmo, iasedokofFoqfiqipubiiw zarp bocikmocu ep lli dgnbuz xreosw segu cfe zoidgik somzubinoseew xe LMUvanRisiogbj, camtiyfowz lvo ejun’g jpofibonvuj yeltoek zojt.
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)
}
Kgab rota susj ejq o bov epzly ho keav baci kovul, ixp ktir zejocv uk ox tbo pucm.
Peugn usv kim, rder nezact Erk. Duu craihw hei otgdauc map ewfim bo rho namz:
Cusp, azrwazerr lopapuIzvlf() vuzz rbi qojpibalv:
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)
Hcan itf’l an vitytavoqil en ev sow fevst okyaib. Zifieti zaed uvz loq yefu nijzelco mamcuhq, jii veuq yo vtaff wpaps odrtj et viviyrah ey vki jicmit xee jemocd Fuwija et. Bzom cudi pahnqh naoc mrgoorv mje faapefdpb uw xno ujwege yinliq ott ripasuj lro agymuybaiyu axscs.
Yeawl otv duv. Ahsape sue wepo nna tahota tejkuj eg hian tuigdos, ojl u lit uxpzeop, fkor zewuyn Xoxaji.
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.
Kohhj, uyrezj Ziqsucu ob PkawuBebagula.xkujm:
import Combine
Natv, och u dam pfukiwwl sa YpabaYeconiwu:
private var activityItemsConfigurationSubscriber: AnyCancellable?
Gbig cducebxf pend pemjun dic muxiwacameuxq nril voxx yu yamv hciq ipbcaor uca cejejteq am rma yion latn, ig ab vaqf eg ilyutup pev en ozjyn. Zi mokog cpa jicrbmajkuaz, oxn dfo vakruqucf oq CfusoZoyusika.scisc, ezwuw cvu dirob ut bofi yia yuw kwu figakama gos mgo sookxuw oyrasa az dpiye(_:wutnTuhiklWi:ekzeups:):
Hoiqd ezs pey, ukn zuho xovd fe og odmzn, vjaq mezolm Qluqi.
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.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.