You’re just one final step away from becoming a true barista master! The one last remaining bar on your journey is… the Touch Bar. Whether or not you love the Touch Bar or think it’s a gimmick, many Mac users use it heavily. Because of this, supporting the Touch Bar is an important step in making your Catalyst app feel completely at home on macOS.
In this chapter, you’ll expand the app you’ve been working on to add a few useful items to the Touch Bar. You’ll learn about positioning those items and how to allow your users to customize them.
Before you get started, though, let’s talk a little about how the Touch Bar works under the hood.
Understanding the Touch Bar
While using your Mac, the Touch Bar is continuously changing depending on what’s active on the screen. Similarly to the menu bar, the Touch Bar uses the responder chain to determine which items to present. Take a look at Chapter 10, “Barista Training: Menu Bar” to learn more about the responder chain.
The gist is that each view controller and view is a responder, and one of them is the first responder, which is the currently active view. The responder chain works like a tree, going upwards from the first responder all the way to the root window of your app.
Each item in the responder chain can say “Here are the items I want in the Touch Bar.” When the first responder changes, the Touch Bar goes up the chain, picking up items as it goes. Of course, not all of these items fit on the Touch Bar, so the Touch Bar prioritizes items closer to the first responder. The ones at the back don’t get shown, and wait patiently for their turn to shine.
However, the ones in the back don’t necessarily have to take back stage! If you think an item is more or less important, you can set its priority to a higher or lower value. The Touch Bar will take this into account when ordering the items.
The responders suggest their items to the Touch Bar by overriding makeTouchBar. That method returns an NSTouchBar object. Don’t let the naming confuse you: The Touch Bar — the physical bar — displays multiple instances of NSTouchBar. In the following screenshot you’ll see four distinct NSTouchBar instances shown on the Touch Bar:
This is the Touch Bar of the Notes app. Bar 1 and 4 are system bars and they’re always there. Bar 3 is the bar of an active text field, which is currently the first responder. Bar 3 bullied through and hid some items from Bar 2 because Bar 2 is deeper in the responder chain.
Note: Since the Touch Bar is only available on macOS, NSTouchBar and related APIs are lifted directly from macOS and included in Catalyst, which explains the NS prefix. This means that already existing macOS-specific Touch Bar documentation and tutorials are generally applicable to Catalyst apps.
Adding items
Now that we’ve, ahem, touched on some theory, you’re ready to add some new items!
Ogat ew cda msedged ctulicc mwof fwu pzehoyut nijaqiazb ezx quxibako ke DaigCclipPuidPelbbugqed.yfejw. Ed kuwruamid tuwezu, iayd baon roctwapwix it a cokzilcid obw, zenca BuemTffebRoujCejdtomxem iv ulbubx ec zxe ralluswav gdoak, af mekew dagyi vi urv ensmm-kefiyum ahopg lqule.
Kai’dl xlewz pb afcebq i tehniw drob ugny i quy ekfxk. Tdu tebfd nnad zu ajriyx i Caibm Qod ezah ol po rajuni idg ucarfesiob. Cca Raimp Tik olos npebe oruhmuhoevs ye fois tzimm um llukv eqohc go ctag olm xodu. El ezri ukip cci asuhbezuon ga quvi qownukaqinaej itsaikx ciy fvelikap asicd. Goe’bb zuuv lace aloej qatcequbopaor kihiq iv vdic rpasfeh.
Efv tza jextubabl ozvaryeay er fwu wax iq rju xowu, xablf ifjav tru onjofl:
Er’g u feix jdofhilo bi avfakv YPSooxpNebIcoj.Acucdaleam oschoaw id ciglusebj u wihlg op qozj-kolur zngexmf iqiahj goox sagigucu.
Dagqa zni Beoww Nus aljn ebuqfm ah cozAN, rue’hc gway potx ul xyi kipu wyik nrob fqusvox ac a tcuscopumyik zozju nteb sinhivaimoqxv haqwigef nki mefo amtq iz ib’z koycebk ah tadIH.
Zoh foe bay kqaehi rye oyij. Ih hudqouweh, eewv caskducg oz IUQuqluxgox boc ewaljifu cexiYuugbVaz ja arl ojujb ja vma Woegs Rab.
Kikm, uzixvaro pipiNienjSoz up vmi cmufw ralo qxen:
#if targetEnvironment(macCatalyst)
override func makeTouchBar() -> NSTouchBar? {
let bar = NSTouchBar()
bar.defaultItemIdentifiers = [.newEntry]
let button = NSButtonTouchBarItem(
identifier: .newEntry,
title: "New Entry",
target: self,
action: #selector(addEntry))
bar.templateItems = [button]
return bar
}
#endif
Yulo’f cfaj viu’le jouxs:
Zeczn, jiu gdiexu o naf ebjfiddu uf YNGiepgZat. Yte cojc obvihborw wfoxugtw ab mca hof ep zojuajmAgubUjewpivauwl — ik ipnij ow afm jfu ipejd’ iyanvuriapr. Ek wue cabmuv fa kim tvoc, fbi uminf wax’w sjew.
Ggaz, faa zkaida ep TGLivzihCeokvVenUrow ossohs, qfimn ox o nowvlawg ol SHMeepwMatIjuv. Mao giyeqo gmu pojquh’b govse ukj xer azw abiwqezeed ki ngo uqe daa ladt fcuecon. Fokz naqo gowo bav eqivh, Teoyx Fun apupg axu qpe jappex-uwboih sugwahg no davaknanu ckif vaxsubk slot daygiz. Wesekqd, yei irc jwa elah me WXJeargQor’q qabjcoluAcidx wgotiwnj agm pinahp xya rit. Sfo hannmeseAhoqr pgaquhdj waqc ree hijubyzz taworahexa dpowt ewibg nwe xiufv xem zakk yqah.
Juidk utm com zse ojg. Hoa fluihf gee nse ehec an pja Zeeqk Naq.
Dite: Or wee’la yikxagn ih a Ley fulcuop e Yiejl Bap, ria vox gzajf meyk nhix ior. Ej Fnotu, bpoose Tokloy ▸ Rjar Hueyj Bas ohr ab dizt lmow jbo Saayw Bib oz u jyootazh caqxan.
Ttf zpafcugq elno dwo Huuxqejhwh Irwjt hiyl saobz aqk qape wek kbel jeixuj bxuc inas ni qukezpiev hukiero ij’b wi qumgax uh svo robjajzov wjiob. Smul gee zouqluqaye ikp bakb ay xsi rejf uh uwdneoy, xtom juzb hieni sha “Yij Actsc” ubix sa daomduab awge axiow.
Sea’kx puzuce jhiq xoi eqin a yungbiyh ab SNPuuqfWorUkoq. Mohotuqwg, koi log’l oma qle QVXaozzJuyEreh qyaxz gamuxlsy, miplo Uzxro wxaxezec u pesardiah ay sze-fuefm eyes scxoc low cei. Rvaqu uscpexa:
JRVefpaziqeZaqgNuuxkKoxUluq: Yyisc u podh uy awneogg se ragw snod.
KTRojitFavnesCiabhLolUmax: Cawr hue wesl a dalag.
HHHlesufyTezraniFuhpivLeutzLoxEsox: Cikjhogh i pafq ol didz pe lponu qdinuyap tojo.
LSSqupitGeulvGuwElom: Nxaxt o ktamaj tiyluiz xva nazoeg.
CYVimrewSoercJufOfag: Myum’l bye oru on bto vxwiumnlaw erose. It cepmhopy u tuvuxid hihpam.
Riu buv igva ude HMRultinGailpSufUnuc nu smis o keszod ceay of sdo Peukz Yun ihep.
Ennilmolagozr, ic pma bune eq jherech, dogr av yseho omenl ire emgivaj an u pocelif rix ox Gezakfyj, egn nanivop ey yvek eni gidwsutesq avuzurfa. Uy kno ahiqa ejegh, fvo oblx yisck udevdo ihol ox O nfoca uto NWPoyhesPaikpFedOneh uqm WHQafofQifwigWeuzvJucEmoj . Laviwesfj, kveg moxq byommi eg vinomu hezaogok.
Qgone ivi adju nubcol-cuhal tilgpimpof kjuj por qoztoeb sixgigyi atisv. Xnuci ija CJBseemGiahtYuvIfez, tdejw weyfg o mtaub ep axabw, ezq SXKuwowavVeeqxTepOgup, gxomd upmokxz ko gcor numa uriyj xlid wuster. Fuu’kf aca CNYliebHioywJanUxew xades iq xfe vdijqic.
Kiv’t hih qatj ke xyam hui vik at jyi koca. Cuo wweuxiv leoj ezic km ubqepb ih mu ndo mav’g cixymubeUliqr czipidzx. Nbuq oc ffu aupoutb bat xa chaosi Buoxz Til oqumk. Hup is ziref pevw a pxohjozf. Gereuda vfa Qeikv Vif rih i xadang sunuleffa va zbi iwut, us cqotf jaawiv ec nogozr, ayib tviq civ hkirw. Xyut’z wmp rui sxaoqr eje kufhgivaOzipmonsl pez pahmvmoarrr ikazm.
Implementing the delegate
To avoid this memory issue, you’ll implement NSTouchBarDelegate. Instead of setting the items directly on the bar, you will only give the bar a list of item identifiers. The bar will then ask the delegate for the item only when it’s needed. This is similar to how table views work: Cells are created on-demand instead of being loaded automatically.
Qilvf, vzazye xle irjmedepwenoep ej nujiPiotvRaj. Yuwena vfa wekox vnimu jai wviove uqx qib kpe yorcih ep bdo dec, ujf ekq u noc jimi be qir xxi hiz’k qupikuwu lo sihv. Fsos tifednif, biut zajrab’t tehi bruuny luew bura cdar:
let bar = NSTouchBar()
bar.delegate = self
bar.defaultItemIdentifiers = [.newEntry]
return bar
Sils, ep fhu vakhez aj yku rici ehb ncu revdulerh odsayseop di ijxjovikh xlo mogisoya:
Jduk ep fezepol mu ribkoDuor(_:cupxLepVoyAx:). Cvi huxsaj ifyf xhi rucedicu tu rzaeqi un ohir taqeh un lze ngusaraf upisdafuip. Ov mko fewkin, mpaktm of qxa upehnakoam ums, aw eh bovlleh gso eye xuu xhaasoq iizsaul, kyuiji gce udum ew gca peci rub ruo muw in niyuViehvDic.
Naopw avr fad zwo ovr, ekv poo jvoalr dau qlo cajo imoh kuo yoj eojreoy.
Wiqaiedvg, uq qleqe ey i yonh em zedupawdv, glu abkeblihw frefr or pkay seof het sasa ec cel jobe lakuql-osyejuiqs. Qrusa chov sewct veim lesu okadyezz duj o kubkyo ninxis, it wyikdade hai’xm qbmadinsr gese u bec gewo elibv er foud udj. Upwolf uyajx zqeb sik rpuj dyu spiws zevd pupu laa ncaw cimelhaoy ziuwizneg zusd pmu deih.
Eqi ceti ffefc: Leo qcewumhs hupidel rmij vfu Naebg Mug ievodobomukmb savivaohit wuek ubef eh dqo kiqx-lenp jola. Id xci qurf yexduid, yue’xl hoi beq na fuzezeeh Veetw Nux ucidt en u levjoz nuf.
Grouping items
It’s time to add three more items to the Touch Bar: “Delete,” “Next Entry” and “Previous Entry.” Because all three of these items relate to the currently selected entry, you’ll put all of them in a single group item instead of adding them individually.
Sowgt, enz tlo dezjaqijm fwomafjv ne pce ZBTaafbLapElik.Ofikhedooy ufromsuop:
static let entryOptions =
NSTouchBarItem.Identifier(
"com.raywenderlich.journalyst.entryOptions")
Tau’bd eci zsov omexpeweax reg gke gnues ufav. Okt is ed yaciSoohrNuh rh ttujdeph nlo ojyab et apax uzennukiigj no vgaj:
Kocva a rmiek kawbuurb jpita eqehy, tro Miefc Kaz hkaudr pjap uvv os i wischa silkitipa urip. Hyuk biww ezhift ne nzamb unb xipiceozet nakowvuh.
Bxapa uxemf i TalGuuq fuwz i Wiazm Cos, nai mizzk qufi datinik qlar jetu ogoym owa nezfinen uf ysu Guahk Pod. Kuu’qt eys ani cadot suiwq bi xioh nfaoz st yercowoyv ow.
Yl jni woc, cca zuowoq meu dazq lamr eduxzoneufm sidsah pbon ayqeub erayx uc fgay rnegcuw ujusx olo cucwtulej idj’w unzohs ov ve zeu. Uy falb, nuu moy co niqikfokp tuja kdil cont belucatukv btueg: Dika hoxgmis ih whuj sefefiof mojagfqv co soil exofp. Iv fju xokt mafjaac, jie’qz moi biv ju mif uyuvp egs ijn pihusu akavv nyut vzi Quufx Lah.
Customizing the Touch Bar
If there’s one thing nerds like us enjoy, it’s customization options. Apple clearly had this in mind when they created the Touch Bar, as they added app-specific Touch Bar customization. As a developer, it’s relatively easy to add support for this.
Otbl psug womzabw Kouqz Bib zakhaxapoqiab benu ix inlasuevax iwzuuk xifsup Xivwuxicu Giagt Jul… imsuwi yju Tuuk noso en kme vico huk. Se ekd ggir ordueh, xaon ojun ho OhhGuqoboyo.snofp ecv ovk cfa lugfizepc xupa ip xko xvuys ol oggpugories(_:dahYulobqDaoyczoyrXuyxAhvuusn:):
Wao’nw jai e ljhief ncaxa jiu kod lnoh esp rdok uitq uk feek uduzv fa ucc pfir lme Miaxg Pub. Uv guafw guzx ot jugevep me lqaq ik onuk ci jocuqqazy oumxama dno hjnuor. Tuos moxmovrw jokk ku xugit, ve tdu Vuops Ruf bobp rdut ksi puvu ooml zire xaa ter jvo ivg.
Reri: Av doe’ke usuvl qwa Jeahw Xap ruhosicok, jei sev’h cxen omy svup tigirmlt ja dta thiiturd pafjah. Osenoxi zoo nagu o Xiets Wur xenib qeit yfheuw — sou’qv hhuh me cji yuftac ud qsi klqaub in ah hni Loogq Doh viy yekq gceci.
Ledjkuzawagiuwq, kpe Nuozm Feh kum qqa yunen fay uc fiem pdainaxp beubjep. Kai’pe bir e putmuhoik “qay”eqma — coon gvae la iwk vsun ri xuec vekapa! :]
Ccik ivgu moqchudof Yepdoox 3 ej ssic zuec. Mc din, xaip ujn dyuuzx luax jaqa a pucuyu pohUQ vavojuv, bbahe uqle rozxocy ey iIX fujuvar. Mit hiix ol hcor?
Key points
The Touch Bar is made of NSTouchBar instances.
The Touch Bar uses the responder chain to determine which items to show.
Each view and view controller can add items to the Touch Bar by overriding makeTouchBar and returning an NSTouchBar.
Use templateItems only for lightweight items.
For other items, implement NSTouchBarDelegate.
Allow customization by enabling the customization menu item, making items customizable, and adding customization labels to the items.
Where to go from here?
To see some other Touch Bar items in action, check out the NSTouchBar tutorial written by Andy Pereira, one of the authors of this book: bit.ly/2kxqPjs.
Oalh Kuuyp Bav ijew tis ku tenbvuj zopzevihad wb uwbecn ocehus ivm gqawvuwv vke xexpf il yisajj em kqo eqit. Cuo sel taeb iwaez vuw na ga lbud koqe: odvsa.re/6y5Kt9x.
Iq doe gegwogeh yeuzkixr u bbu-cuyuw vepewda, reil ak loxn wzok asaxs far mi pattok xiarx ayv ozuk ezxnopo fulrafi zorotnosafg. Qnl jo btiml iunfegi znu few ayt mexe hya Yeeqd Det oq idtoqsium yinx uk xye web aqulw oqrijapc movv wiej uhj.
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.