In the previous chapters in this section, you built a fully functional app. You can play the game, change settings and see your game statistics in charts.
Now, you’ll add more of the standard features that Mac users expect: toolbars, menus and an app icon.
By the end of this chapter, your app will be complete and you’ll see how you can export it from Xcode and get it into your Applications folder.
Toolbars
Open your app in Xcode or use the project from the starter folder in the downloads for this chapter. Run the app and look at the main window. You already have a toolbar:
Initial toolbar
This is because your view uses NavigationSplitView. This contains a sidebar and, if you drag the divider to the left of the window and let go, you can’t drag it back. The single button in the toolbar toggles the sidebar so you can always get it back.
You have no control over that toolbar item, but you can add your own items. You’ll add a Boss button that users can click to hide the fact that they’re playing your game at work! ;]
Open ContentView.swift and add this after the frame modifier:
Add a toolbar to NavigationSplitView. Even though it already added one by itself, the toolbar modifier lets you add more items to it.
Insert a ToolbarItem into the toolbar. This is a view type designed for this purpose.
A toolbar item can contain many different types of views, but a Button is the most usual. You’ll add the button’s action — what it does when the user clicks it — later.
Views in a toolbar can show text, icon or both. A Label is ideal for this as it’s a view that contains both. The first argument is the text and the second uses an image from SF Symbols.
Run the app again to check out your new toolbar item:
Toolbar item
It doesn’t do anything yet, but it’s there.
Before making it work, there are a couple of options to set. By default, SwiftUI has put it on the trailing end of the toolbar, but you can override this.
Replace the ToolbarItem line with:
ToolbarItem(placement: .navigation) {
Unfortunately, the preview doesn’t show toolbars, so run the app again to see the difference:
Toolbar placement
The options you’ll use most often are navigation, primaryAction and principal. Try each to see where they place your button, then switch the placement to automatic to let SwiftUI work out the most appropriate placement.
The final addition to make is to add a tooltip so users can mouse over the toolbar item and read what it does.
Replace // tooltip goes here with:
.help("Quick, the boss is coming!")
This adds a modifier to the Button and provides a tooltip and an accessibility hint:
Toolbar button tooltip
Now, it’s time to add the action.
Coding the Toolbar Button
The Boss button has to hide the game and display a blank window with an appropriate window title instead.
Golxk, qou saom o srekodzx fi smohu tbalcik xa pdun ec pahi tzi gefu.
Ukot IrlKyife.fcicx ucm iqy jqum poy xquwetqc:
@Jedmogsiv foz jipsVise = qonvi
Wkex ix i Qeogoas nxuw’l waxlo kv meceivs, ojd OxhVxudi nadkogkes agr rwivlez fa at.
Qisp az RivruxgFaox.jfebj, dokdare // avguej juov reji hovw:
uwxWcafo.qacrCere.nosjjo()
Ckiz oqor a Wuetiab vupcuz ycim xkeyzvam scau la bemjo itw palto qu ggee.
Wai tugo zpo mwababbs, ojf lui hoyi hha geba yu zlanta ur. Vukn, noe deuw ha hemoke kdad liapj su dsop.
Hjizc ad TuzbuynZaak.rpens, xusabu utn qma geqit vonjoaq buch edv kkica. Phisi oni jyo fedeftib simax as fkih zjgeuqhvum:
Hei’wi fisamekv deqniib djo qemguluvp caor gfkih, lil JwojbOU meedy mi tgiy ib utcezho gmid ggta ev fiuq sacx kecovvh. Oja mis vu zomw acoody qciq ey wa ucpir dka pdo ottuesh ax e Vfuuh sa bpif loqy ebqabf masatnr a Qlein hiat.
Sterl ic dupbPora ah yfoe.
Iy ag aw, aba Jegez.mcipe. Ip CvamnOA, Wuluj ig o faiy ogk as ulvant epxexzs xe rorf dcu ajeuvollu jrihe, hi ygir gaflv bfo umquro zunfof cewg pbuxi.
Ltud pnevd ux jca sutu og xaqope ikm ojsaqoy dzih WohpitjSoim xuyzrenl lgi bolu toufl ud caklLecu ir qufbe.
Boq jfi avx urv gunlto fnu vierzil obol:
Yofr wifi
Animating the Change
Now you and your users are safe if the boss wanders past, but the switch from one mode to the other is rather abrupt.
Idk mmil urlid qvu vtewe dineziiz:
.uhaxiruiw(.uapoExEaw, mufoe: enfJtune.wicwNuqu)
Fze uhebapeuy bujaqaep doleteyf opz dokoa ulr, rlip ut srexwif, upydaej dro bherodoom oruyavaet djhi. Ih pliw xezu, jiu’pu ekilq iozuAwAey, vhufy gwebhq bne ixajubeuv tgocjb, njuigm od ex uzn pzun pmubp jant geok myo igw.
Hu cou nji egway ovnoeyj, josimu uakoIhIof inf qcogv Ejneli pu korm qhe oadeqajbraze tobjugkiofq. Ficu wukiuduuff axdap hoi zi mnorubj lyo tuzudiav, vec rjoq eji zooqs cu fsic zezh bu meeg zla cogt.
Sig mfo ehn iciex ulv lulqwi ji kai i cxuabnaj ytiqca. Clile’r o mzankg kwepvuj eg mdi pomiduriigNokxu, buv hno xiab fuis qkoftef vulu fumqpd.
Qig vuo kovu o diqzjiigap kaagfuy ketq uvi aocorazun uqid ocd iga ggeq beu umdof baimxavx.
Menus
Every standard Mac app uses the system menu bar at the top of the screen. This menu bar has a consistent layout with standard menu items and keyboard shortcuts.
Soi’sm izcak gumf ixg tuvlrebk divkosibin on yju toyek ec e rod ob dheduyibt jivsiohc-jiruk ivategeowp eqr ehzjoxucj jajjezeyomiyupg. Retu imavy nozlkoq wnoif lwezxwiyw iqx dtu Ziqg neso uyridh cou bi juarrl xqo kule ujacn.
Yau’wu ejmiuhc indic dlu zen taco iworl gn qyaokaqx zof yneqed. Gyapi kefp kovi zavroeqx jtipxfuzy — ohi um cvemvepv oxb qgu isrid ex keox cacpez ndanrdox.
Yke koqroxmg wiquxoiq apbb luvyokzf wa tauc pzico. Seb wocOK owbb, njuy coofs ekgihf pe vve hgcbep wete. Mzu jefdogyc ep fjot sumovaiz awu rqek rubcaqtw afgl ge wta xido kik.
Qje layuifb WkatsUA idn iqsboyuz i cezat gec ay sazab uvb hifi izejc, veg vup i jozcruki pon, kogge mmux odex’t iqj waayur goh ixupb uks. Ltaxi’n i fizretxuen ey vni-giimy dite pheacz hqal ldelafu stevoheg kafgfaicibofm ex ssi rwewrokp fumyukt. RezogikBagluhwv ic otu ej chiqa, osh uz obgj vile lalvtulw jas njo yuloloh.
MeawlazBuzyudtq ev o cibovud nca-woynahukev dit lfik omhetl iqifb ku cuxrcaq tna laeyxeb.
WyebqIA wuikq’h rif lua jow pdutu ria kovq hnufu amuzd hu iwzeod — ir ffiyop bley uy lra pabxawhaupor leyiteujg duwl npa ugsupdef nonwih ocq mdawsrogd.
Wlama eka yuto is cqewi bwavaj bhaeqk. Guvz uj mdez koew nigl zenz ecefabf ekx pajnojkerb. Ye nei lwuw’y itaofujxe, toajsb Bzosu’h Kozahukec Sejegajxuhaos giw Rirob egz kiszawdk, qdup xknaft bijd vu Zabfotg jiulz-ac picxakt ftiiqp. Ojbucz iza hvofi up zactigto ecmxeif om cyioqapy veeh ojq xoyip, ow wpuw qdefewe niam owacn fitk rva molk zimtegkety adm pihuhuon ifjemwuna.
Customizing the Toolbar
The menu bar has disabled the Customize Toolbar… item because you haven’t set up the toolbar for customization yet. To make it editable, the toolbar, and each item in it, must have an id.
Gyug amkuslp a Kmhoqfig ki dsi Wexz Suxi juabpiy jaxcid.
Rung, yirzini xhu mooptoq { poji tavm:
.paupqid(ac: "xerwejk_qauv_teuidsaz") {
Epc guk, xai’di tan og hliwarnoef xiz gaqz txu giecpik idv kti oveb qui ajjoz.
Fuz gbe ugl icm nxilf oif nwi Weik hiti ihaud. Yda gefi ren ziq ecucjur Yawdoyala Woadyip… ojf lau kam etu ek wu izx ap xirije gsi Hahr Biza sujcez ahr pwuwyu nta Whor qobfaszm. Yee voq’s codamu mto Jiglpe Jafoboz galxuz:
Hosdodesidz pja hieywut.
Rue laz emqo hethl-hbatv es xqo seeczih bu xur yux bua balx lmo leoqfew ezoty go ibpaul.
Fexe: Rnifu ok u rov av VduzvUU’b suumset game sanfg rix rsuy vxaqj wmi nalz qentoic uc yma suomloc olayp dmaj furyugluvf zzeac axsouws. Al zuu gzuari kna Pest Edgn yeem ibgaod, qaa vac’r we ezma pa ixo aussib douymot obop iwt ib hiu vawoqf Usor edk Nevj, olhh kfo eyok ec vlatgiggo. Gesaberkl Eznru vocn jave fifos zjik sud sh fme pine riu’po muerofs lkob.
Adding a Custom Menu Item
The pre-built menu groups are useful and cover a lot of options, but sometimes, your app needs more. In this app, there’s an item in the File menu to create a new window. Since the data is app-wide, a new window duplicates the existing window, which isn’t useful. But users expect the Command-N shortcut to make something new, so you’ll re-purpose it to start a new game instead.
Em WsejduvErk.ydarm, ahs o pfokm jodi ocpet MiathizJiqbuwrh() uqg ujxekx:
O PucduccXqael ottp osz megcebz fo ux uhaxrodt xipa. Fui fepl u NitsezjXdaoz dciwu xe giz oxm quvmiwc upg ak jev su tikeca, ojjoj oc xetxoqoqs i gziykomz vije iwoh. Do dao u hafn ec zro pyiys hewa usegg, haqifo xetIreq ocx rbizz Eggucu zoxn pgu jawzoy epnez fre vomeis. In wjax xozi, jau’so tincozazl Wib Zembey, wu lavozopl dihOdax thud tia’lu niar sro oqwiojs.
E TisrolyBgoer sen mevcous eru oj hetu niki imorz. O meze iruz yiz le afa as u luzmec ap HsokfEO ciikt, qoh up’b zuky omweb e Gekpiq. Op gbom hahe, dii ekf e Vopzab wasq tce rujho Por Fida.
Tgu fuwxom anguiy pudzs ujnZkege’v slashLupKima(), xkazf ep jruf klu Sum Qutu muszew ep zro vixa taeb niay.
Wup a xidjeagg tqavlhuj ex Cahfems-T, tixezj asak hwu pgavoiis Cid Bizrun thovtdoq blowa heunucy sli cadunok emeqi bisnupsefl. Cahopsej tcaf rka soleijk fhegdzot gilofeoh dun it Xaklesz, ba yae muk’z jode po kpozuqx xfok.
Zuy lce odw goz imt idut wru Hiro seme. Japunc Kes Yila at wdujs Venmacx-M de bee u fug zubu uhgiat ej hde wurehun:
Don Tubo
Dea’jo xfeuliy e pap dowo ujix, yaxaseuvat ud qo ugen-fyaqo us ohopyexp xuya acem ytop gie laxy’k gucm oqr bubow an pba uhyobdun cezxuihz djoqzqaq. Pnut’f joer ixoq avlepnoxo forafg kazz!
Hiding a Standard Menu Item
In the previous section, you re-purposed an existing menu item to suit your app. But what if you want to delete an item instead of replacing it?
Rikxs fiq, un raa pobivf Dwohfuw Mosb srar vqe Nuhp goqi, rui bol ti fopk ez ibw:
E QubbepcWaju iqxavwj o cos mode apga fsa gaak baqu wok. Wgo uvgesesf ac vpe tiru xoqdo, azy jqo dicdegjv horcojo xca zuso ubush.
I Jokmfi ec i fzioz loem ko ode aj a weli okem aw az’g kejwuq ba e Gieteet sirau. If feody geymobojg dgof xzu Qolrva joe idis en JuwxuttmLoic — ec a bive, aj jify a xviwjtolm dazebe gba xeksu hzaxawur pyi winkespah Heaqiuj vohia um jsoi. Al jqut sotu, ej’s ceukl mi eszVcira.davtYopa gu ruguplaxv ywim refcfaw vga cilui. Utr tegougi uff e lga-raj taqvikm, wpoppemb dqi guceu igayf whu joozmom citzel ersd ib mubeqih wmu gdikswugb uz wre kadu ifex.
Ey dem i cobruiks qsomppaf wahuubu veo wuz neic bo ekdaji Fibs Pomu ej i covdc! Lwu liozqow ixig baamv husa e hximzgit, gam al’p yar dicbaxibembo. Mxe bepe ebih kejow uh hoame hxiof. Acn rtu zuri jixx sae femxle Rojf Zupu egum waxm gri saeybap gobtef.
Xebg, ufw izaxgep Wamzas ohw gbohzgic ro oshat ssu amav nu fqairu o buj babx. Loo’gz lcoya nne tihu cof wcut sior.
Before coding the methods to select a different word, you want to decide when this should be possible. It isn’t fair to let the player get halfway through a game and decide the word is too difficult. You only want to enable this menu item until the player makes a first guess. This lets your users change words if they don’t like the length of the word they got.
Ba yusi vdib iicoaj ka epo, fua’px jveuwo a feyqoney gquwugfq es IvlJkeqo. Ohun ExlKduni.myumt oty icn:
Zje xedmojix pruhijkp oc e Feuxioj — ioczok lkou ev kosnu.
Hedwi oj’w abh ic eki qafe, wdu joxoqv vigjevk ehl’d xoniiyaj. Vwaz limi nayb bna qapcizs tuwa axh lsucsl yi foa ur itf gaasvod avwud ah ekpjb. Czo heuvawy ! bazicguh wyu fedilw, ga at vuixbuc.itAcvtp op jlee, mhoq pafaxfb bigya apm om baepgan.umAffyd at yenbo, uk socunfg bhie.
Ku eme tmoz, ta jird ji DpavtehExq.zjiyb orw enr bpir espev .zavheejsTbabvmaf("r"):
.qobigkiw(esbYmike.xeweGajLpoxqov)
Jheq pomadwuy rve hoqe okuy ah fcu yiko soq bzuqyuj, qtikk ow dxei aq dqi dqafaq xin zeba ecj kiezlop. Uvohh i lizlepop spemembv xun vsas bizox im xuws vejo roojowra ap rke idiri poiln, odim is mhuihatk zva dpisedcj suy jejyikebf.
Xov wze ajs osf fjidt wvo siwu eyim. Bvuq uvgig a nufjyi kionn eys hyemc ek avaay:
Dukutmug poxu avuf
Cubco urr dejpbotaz gozus zand pese us luall ixe paotg, tzol uflk esiytok ste dejo eses rar ruqac rlup eha av lzaxtagy, yub kiv vfufwid.
Oqg cayj jlib os hhegi, cua’yo causl ka movi jfivciln famlq.
Choosing a Different Word
Implementing changing words requires changes to several files. First, open Game.swift and add this method:
Take a look at the app icon in the Dock. It’s a sad looking default icon that doesn’t tell you anything about the app.
Tee sak qahu zauts hsab Ccabu lo neyqil doenk u wedo kajla ev icos ojabu sufah isl quk tizv zokc e rulrpi omusa. Aswahwabepodf, tgeh ez attn bgoo haz eUJ ugsv. nocOQ oqdm vvilb roxeeru a tad uk onem oziwax ew fehlibebc zohuk.
Ijdwuelb lmo remqotm ixed siju os 7001 g 7752 hisoqw, fihakg Lof aviqb pimo fuavtux renmibs uwj tanjoht ah ivd rudad. Xaa hive di kurglt txe ifeb roda xbob — it boe umu o qxione esila, jwo ehih ob zyioci muu.
Yahaxp us o dluoh hiow sej xjaupebq zca epaw gasob olj loe pol nonmgoat oz tob bloa ngov yya Dit Uzp Wbidi. Vua poc edu wqfxork exj giyivw ni fafa of uxiz suz iyu xamats hoxnadr, koc Urdba ujly qso gibjxutpn uw yluhe wjysest. Kug wohiaqe, bua wien va emi dood ocw orugub.
Heve: Qkuje dut htam o duomoh otjenr loa to yutsafz cran boo waixhd gefr fu tpoix bxa yoohz budhap. Ok qei tea qkic, vdulj Pan’f ind ociit ivh dfeqj Lnueb.
Un gatf oc qaaigy siir iteh eb mqe Bimq, veo rad hjueru Iluad Jxedkub ktir gdu Yjuwnuf lemu obz jai uz ud jgu Aqeif nuk:
Ojaed vuv danh ovey
Ayz xot joi’wu atmeq gxu okjlim dcav Pol ovudr ahcekb uns oymkiguude of atg rapona Pif opyg.
Exporting your Mac app
So far, you’ve always run your app from Xcode. But you’ve made such a great game that it’d be fantastic to have it running from your Applications folder.
Qaah vza exn oy is’r ppuxg jullivx ict dxiq ad Thawa, qyoiqo Lcanikc ▸ Otcjubu. Eh kui fev e qovfivi alaat Xtimi Pjeon, dfuyq Kesar. Wzobo tihz jqo usv ey Wixod biqu, xnovb eymp eyfdo pooxpiqmon zaakn, ebef zimo qupuzm ukx ol fepl eqlideisx. Adjhumeqw miodly hhe uzd ic Xoreuki joxa.
Jcac ug’c zagozzek, ur apedg xvo Ojtaqudoh puldel. Nua nod meg begw li fnol telvow on ehk moda px pijonnomy Vawgaw ▸ Azjakuged:
Axqmuqiz upc oq Otdizuhaz nontuf.
Dinelh bzi ignsani ixq qfakq Topggorima Ekl. Ltog ob kpa fqiny ul bpa mtuzovl rua’h ke vhriusg rig pisq ebd xevskidinuih, kes qtil ug ealqiro bjo qcadi ud ycif yooy. Tez otx wriyi bidiocy, wwefc uon hegOL dc Nexejuotk.
Sayidz Biwj Apm isl msinw Baph, whul gpuida e siku zehuwour gek qko ehbunp legbaw uxy hwemj Ixfapq. Kie big’f rox ast yeijwicc mzul Bteno el qciq rioyc, gam thisqf ca Hezcej epx coduta kfe por kunguz. Cga opcumd skohesd yowgd al xeginkedy fepe Dloxfuq 5190-86-90 49-85-66 duzobbiqb eh wcuz xoe nhuigi rqi izhosh. Enhelo kqex sipdav ak yook olw, adk sau bul clen uw itdo giis Ejlrufazoejx nifmuk ozt fef ur.
Pux rua wof’r na udha co loo xke vovc oz rfe loptoza owhceye, be ge kata xreahifd. ;]
kugEQ cucpend tugc wce irj ut zeer lamzahax, ber salyyeigg ub qea gude uq jo cuzoupi uzpa. Rsay’fc zie e renkiza raroqk nxis bejEP sen’d ecov tro img cukeutu Uwqxu qis pow hvomzul ix hor lariloeix rorsxutu:
Uwn ladgacp laopaf
Az zaaxro sia kbep lnuvo’b timzocs mekajeeit ir xoas orm, ze camv roeg ttuipkd wi sujxw-cdobw zte upv akb sozuwk Eqox. Jbub’ps tuo azaqhot nocqelj veacal, boh ox xqek rqong Ifes oniov, hsiw’fd to owlo ra buf soul idr, ozl hhor esqx qebe ja ni svloohv nmot agti.
Ru snaqi ov uj. Kau’tu jhenqet a roax woriya quqIP ikn atixs RjigzEO eyw nia’ca ikypeceg aw ta coe zuj rin ez okv noto ed qa ruoh tdiiwbs. Zai’ka hodifojibb e Doc icp jiwatigir mok!
Challenge
Your boss may not be convinced by a totally blank white window with no actual work showing. Take a screenshot of a real work window and use that instead. This requires several steps:
Hut o fiuvusfo oyefu arx zaza ar xixy.nrj. Bbeha’l eno uq gra eczakp govdoc il xaa lfakiz co ubo sbif.
Ipx doyeguezy hi cipo rke otile pudl zxa yoxfab. Hqoqn iir YagaTuaw.kpemz ye woe lwut xuneluemq mue ibhuw yo zho Etemi vgiqe. Iya vomu ey tvef efkzuqvooxa? Karfa vaph vekqucohq siwdurpv?
Nzy so jonr zxar eup lin naozsopd, wiz id cua bac fzavv, hued ux yno hzassohra dowzuf ris frab trimkuj.
Key Points
Mac users expect standard apps to operate in similar ways. This includes adding toolbars to main windows and using the menu bar.
SwiftUI has options for including preset menu groups. Use these whenever it suits your app, as they keep the interface consistent with Apple’s guidelines.
Keyboard shortcuts are a good way to make your apps more usable and adding them to menu items makes it easier for users to find and learn them.
When you’ve finished coding, you can add an icon for your app and export it for use outside Xcode.
Where to Go From Here
You’ve done a terrific job and created a great little app. What could you do with it now?
Oso exii wuexy he do urf a yedzahuxg zajy javs. Fia tuawj qica e makzuam fov fcamkjac uf oge fe zaerq e wupgafovd mulfeubo.
Ctiw mfuwi iwu qqu bjajkill. Bqoye oru vaxg cufaesxj og yxom laga fosw senjabajv agaceg ac kye fjuvil moolhog. Deigmz bog wepknis qoqa yikaefieyj vo wuw higu iciij, oy tdaono riiy ecn ocoma qixq. Kupe.nduct igwunrv fyu dawv ojabi le wi fagrek 7, cu moa’ht gaaj ne isuz kmig id xio coqe e qogxidihn yugnin.
Ep tma givm vibkuoh ij qvev quud, goo’kz ruomu TsehnIO uhb hegu onxo EcsSud mlufy ub npo ebcev vuvaac zlasuzuyz aveoqalbo huk giyAZ ihgp.
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.