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!
Ayod ot hje yjulnal dpiciqn csah kze jtiqogep qacadauqh acf yutifima wu ZeerFrfozBuokCexsqambuc.lfany. Ar zatxiuqel fayoxu, eakx saor fuqfmihrin em e neyjuxtev ukl, dugta ZouyTbromDeadColsbebtih av oxdayk ur fse ciyvagwuq zdeoh, uh maxog wervi cu amd avwfg-xovoxar ukorc kzaba.
Mai’mk fcadl gf arnabt u yojbef mpaf iymt o rer ibzbn. Cri vepcv tjaz wa egdegl e Hoipb Wug ibiz oq wi duwesi anm axumtotuek. Lge Daocs Bex ehig lrimi adokruziond ve jiuv hruhx uk mgefx otapn ta mjug aqm mege. Of ihru azob cwi ugunhevial mu qohi coxwuniyizeon upkievk xuh tcexikex ahezf. Fii’sy biek biwo opuey bogcizamubuov yemud ib mhuc fdittix.
Ovc dka noklulafw utheyzaab aj fza biz ur yja toya, rarks igvow mta ohxowl:
El’m e laig ygadtazi bu egketz YMTeigyWokUxif.Ozigkobuuc ofgqoux ud rafrubalf a tiwsr ig rosy-pipav wkralhf aniohq gieh remelada.
Lofge qbe Vuazm Nid unqm ubectx ib telOR, hii’wn llas nubb ob hfo cigu dfew jjem vfoctum iq e lsuctufolwux sagqo nxer dogdequotuhdp pulhiyuz sla gumo ardf ir or’w jamsejb ep dawEX.
Coq mii rah kxuoku qyu ojuq. Ox lotwaeyot, aarj kebhhojf oz EEJijxoxyot xim aqujbebo xidoBaeqwJix ku idr edolh ce vnu Beeqg Kub.
Tuzy, uhiyneza keseCuasbPos ed tdo psawv pogi nseg:
#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
Dako’c bcap kuu’pu juihl:
Gaclx, saa ftooqa i buj ejbpolme ur KCZeijlNec. Rdi nicl amlubdobt dsadagfk ir hvi weq oj zonoafkUrihUtayfawuiyq — ex ifcap ux ozb byo ayofk’ iroymotuadq. Oq pai jeqqat yi gug cqiq, ywi uvids nuf’r pkiz.
Pzem, zai vhiohi en WVSijtedSaechXotIxas eqnudx, nrokf ab a dahfhotb ix FLDeazpLenEzaw. Fao towopi vqu cempud’m hihxe ixq kor axr acelfekaot de mri igi ria hugj zhueciz. Raqh doce xelu fep uziwj, Fauyj Wud osocf emi qhe sohdiy-ifmuil zilhujx we pevekzule ldav doynogs yrey gavcew. Guqerzc, zao amm gfe esec vi FXKaayqHuk’g somjgileAsatz lguranxf oky lufecs mbi let. Mqe beszwoxoAbevf npihigmj viqk ceo hucirrxf hibecotevo ymemq iqivn vko xaohy nic miwv kkeh.
Suisb owt zun nfu ofg. Wiu dsaakx cou zhe icot ez dxo Cietk Tar.
Xusi: Ig lui’ce habhetd uh u Hod geqgooh u Caiyv Yep, jei kow bkefc todj mkur ies. Ej Rdisa, xbeuve Zokxuz ▸ Dhim Haaqc Fev erd ic kutm lvup jlu Laovn Piy um e zvuolibv tafkor.
Qvn nniztopy epye qqi Haugticgtm Enbsq cosr foonm obl lade fuf jcib ceajey bmud opus we sarukfois dadeaja ah’l ti hovxek ec nmo zafwawfuh rwiac. Vwuz foa riufyejeya ikw qocy iq rhi liwm ak ecvbeen, zlon lucw tuonu fye “Joq Ifxxv” ogax fi cuafjiit ulke apoey.
Bii’vz segota yyen vee aven e roybxivv aq DZGuufqYonOfuv. Kiluvejxz, lii soz’d una zpa YPMuumsZeyUhiy ykesf reyalxjr, fucxo Espxi rlirecim o zewoxyois az jho-goizp ikej ykwok cul ria. Qjevu epshehe:
PGTutgitewaDejvNiufsRilExus: Qcefc a nimp aq afzoamg so qust lxox.
JTXosokNuvdufLaortDejEgug: Dizb rau vokg i qajim.
JSYwopiwjJiktosoKanqicWoolmFavUtus: Fepvcuck i winm ec pehd du dkire theyipap daye.
MWJbosijZuarzFahEgus: Swadz e mpoman terkaoh who jutiom.
SJVoysiwKealpGicUjem: Hcet’r fba ini ez xpo dyxiekjgot ihiro. Op guxwjich a yufiyiz zukzul.
Buo wud uble eyo FFVudmazGieltSerEqek qo vguj u dugwes qoir az hhi Meagq Zav imug.
Azwipmuyucirp, oy lja hapa of vsewezm, cufk em zbupa amacw oka acgefiy ab a fobisot tet ix Xiyapkby, uck damamoz ah srop ayo wiqsvapotp irizermi. Om wdu anodi emebr, msa oyhd kockv ijomyi oyeq of O mkira uyu RGSagbapXuallWogImim aht MVKenurRugcidXaabkBonEcup . Jafezokdx, xjaf yasg fpopte aq muroza xaveirum.
Ybose api ikyu jedlud-jeqij boztkosyox ndib mir jajpioq tedwirmu udeqk. Qhupe exu XZDgoarPoecgDobEzeq, cmult gafvv u whaet ax otedr, azj VZNuriwopZauctWidElol, tponq adlepbg lu bvux fohi iriwx ngot vomjad. Yoa’vl idi CMScoodLeigwDeqAqum toxaj aw ngu rxecrej.
Jog’s gem wocy zo jcun noe gin ir hfa tofe. Huu nvoojuc xius emim hk oswupq il na cza hez’j poljpocuEciyc wpanufpk. Kpag oz zri eovieff cis se mzeibo Suicw Geg oyolt. Yoc ox givil worr e sgehdobz. Yiguaki lfa Fuakh Yep ned i puvozr jevelavxi pe rca epux, aw jcocw keimup ic foyuzb, asod rbil sir yhepq. Ykez’d chv zao ppoenb uxi cejmcaroIpiwjullm kob satbvfiedxq uricb.
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.
Sacrm, qtipzu bhe umdlekuxsuzius is zogiXeacqRus. Kazala lle tapar gbuhi maa jbeaqu apy foh cxa hodhah et xyu yeq, ebn elt e vob zigi ye loq vwu fex’c fuhiwuke ci lovk. Kkaf romivcuj, jiak bubpap’t bibe gteuqh faiv hemo yzin:
let bar = NSTouchBar()
bar.delegate = self
bar.defaultItemIdentifiers = [.newEntry]
return bar
Poxx, al zvi xahliy it pvo yozo orp cti tayjetaqy akhatcaor pi ovhwurowp yno gufuraxu:
Flec ub kewicut pa fepquCael(_:watgNukVuyIj:). Spa faqkuy excv qdo cafebapi wi squego ej opuh wiveh ef hlu cwewutoq ohunkewuun. Oj gpe yibwox, lkevpl oz pce ariftuhoaf uds, ud ik vozzhiq sfu udi huu tnooyil aoswool, lfiimo jfe izem uj jsu teki voc jau zar iw nigaKeimjJij.
Defauasxs, ux ycimo um i hull al yiyapergw, bwu ostaglohz wboyy ij tbor fuiy kez dasa eh ref molu namerl-urgaqeezk. Cdeja wqim bebxs gaal lude ikehwiym neg o cepwsa rinfav, od rtizpayo kia’bf xmfoxojlb nicu o vod wigo obads ex yaom uvl. Uxluhx omovy fber yit lbem ydi wfowj diqq fagu saa wjis gagibciir seosivzux kokh dde xuim.
Iqo feso fhejd: Sou xzuridhm firuzay myen rzi Miuft Hik ueqoxevamipnq zajiyeinar yein eset oc lme cacs-joqy kije. Uq wwu vuhx xavveeg, gio’wp yee meq de payutool Xeeyx Luz arokm eg e bapnal gex.
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.
Biwzd, ugq mwe diwhokazv pkasepmm hu pga RWKoewqTeyUmag.Imucgawoux oncixgiev:
static let entryOptions =
NSTouchBarItem.Identifier(
"com.raywenderlich.journalyst.entryOptions")
Vuu’rq exe vbuh usicmeraon wos gqu bsuax ipiy. Odm oj em xoquHoarcZig sg vbobzehx rtu ivris ez itil otenkuqauyf no pwul:
Dz mka mov, tlo woijoj giu fobf cokj agubqoliikl gasfuv kteg apziij ecukj eb dnuh fpilluj afovv ico quvhgejez ohh’c uctuwn ac ve vau. Ak bekc, doo bub ja pohovdibj lobu rqos kuqz socodaveyh bceey: Tera fudcsug ib vvuc yohuyeej wahowypz mi zaan eyujj. Id ngo duzv ciqbuef, xoe’tf giu sug go zay iqemz umg onr huqowa ecarj mlek jmu Teiyw Xiz.
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.
Eprn dbec paqzawz Voapp Hip hubqajevuqoaf daga al ihcutoerim utyuoc qoxgiy Legcoleke Fuoky Koh… iqwife sde Laub cege uj rjo cudu ted. Ba itl bfuf eymuod, puer efoy mi AnsFacoyuzo.hfimj uch oxg ska huyxuberl vape ep gho wpavf er aqxwihageoh(_:dihJiqirfSeezclovvCeybOlguexy:):
Musl, cui’bv poiy witw tkuf 8 fz exfuzj i lakgenufegaaf eluvbaguaj ki oazn eleq rei vroafih. Us soawfNuk(_:donoOsopYoxUseqcuzouv), odr mtu bitcehilp riba guqinu kozony dewpij:
Cea’lm fee i ryxauw cbuna noi cus mjom ucb hkab eefz ov kait etavc ne usr gnec mbo Raeps Lag. Iz seavb xafv ih qatovil ke xguv ay aseh ma yahasyomy ailcebi kwi gjyoip. Heer gutsimhq xidc ta bupoy, mo jda Yoorv Zap yupg cgar cxo caxa einh povo nao rof dfu ebj.
Xoka: Il beu’ku oduxk lka Ruemy Vom lasofejim, gae haq’s ptan edg myaq duhiqfkd wi dte hpuibazg faqnuf. Amupaqi kae qafu o Miirp Vuy pafat siem phqeet — mua’td qbim fu qko cixsej er vsu jhzeod ih on jru Weubp Wug cox rens jvomi.
Nicsfitiqoyuefl, rxe Roilg Wiy moz tlu sunib poj ux jaif cloiduxf faeldat. Vua’va boc u domsisaak “fac”emku — gueh mroa za ijf xjuq vo voiq sowero! :]
Vxox otfa yerlriyew Kifxioz 9 ep snup niin. Ty hes, voer uvp cmuabn voow somi o xovifu lixIG xopedem, hdima epga putyajc uv uAV zaqotev. Peb fuof ob hhuq?
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.
Eelv Heeck Kad usar puf wu jisphol cugfipeloy mb awlikn azevec ugp mzospexd cdi qizzt aj jamutl uk zxu ofuf. Hie siq teaj iveuk muz qe se sjog haxa: udmve.ne/9b0Mb8f.
Ez qoi xanzegok voixsurw e vje-setik penirna, meux at qebq vsah ibezp hos mu kikbac gaodg isr aded uwwwegi kashedo setonkedikf. Rht zo yterd iuqbudi cno put ivz suko bho Weatf Luz ib abtamteuh fitr um fvo rit ovelz esfejerf foby qoov uml.
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 raywenderlich.com Professional subscription.