In the previous chapters, you created a table-based app. Your users can select rows to see more information, and they can search and sort the table.
The app allows users to edit some movie data, and it saves and reloads the changes.
Every Mac app uses the system menu bar at the top of the screen. So far, this app uses the standard set of menus supplied with the AppKit app template. But not all of them are relevant to this app, and there are some additional ones that would be useful.
In this chapter, you’ll learn about editing the menus, adding contextual menus and much more.
Examining the Menu Bar
Open the MovieTables project from the last chapter or use the starter from the downloads for this chapter. Run the app and look at the default menus in the menu bar:
Default menus
Working from left to right:
The Apple menu is part of macOS and not under app control.
The MovieTables menu is standard, so you won’t change it.
The File menu has a lot of items more suited to a document-based app that aren’t useful here.
The Edit menu has a lot of items dealing with formatted text. This app will add text editing later, but it doesn’t need all this.
The Format menu is all about formatting text, so it’s completely unnecessary.
The View menu has some useful items, but since the app doesn’t have tabs or a sidebar, you can trim it.
The Window menu is fine. macOS adds different options to this depending on your hardware, but you don’t need to make any changes.
The Help menu doesn’t show any useful help, but it’s good to have it there for searching the other menus.
When you wrote a SwiftUI app in Section 2, the template supplied a minimal menu bar and you added pre-defined blocks to suit your app.
For an AppKit app, the project template supplies everything, so your first job is to strip out the parts you don’t need.
Open Main.storyboard and select Application Scene in the outline view. This shows the menu bar in the storyboard:
Application Scene
Expand Application Scene ▸ Application ▸ Main Menu ▸ File ▸ Menu in the outline:
Menu structure
The structure takes some deciphering, so select Main Menu and press Command-Option-4 to open the Identity inspector. The Class at the top shows that Main Menu is an NSMenu, which makes sense.
Now select and inspect File. Its class is NSMenuItem, which you probably didn’t expect since it appears to be a menu. But it contains its own Menu and that is an NSMenu. All the objects inside that are NSMenuItems.
So Main Menu is a menu, but the headers you see in the menu bar are menu items, and each of them contains a menu with more menu items. That’s not confusing at all. :]
Now you know where and how the storyboard defines its menus, you can start editing them.
Trimming the Menu Bar
You don’t want the Format menu at all, so select it in the outline view and press Delete. The reason for learning the structure of the menus is to make sure you delete the entire Format menu item and not just its menu.
Os poi cuwuhy Tohnik iw lsu jkonyyoapr imf tmomt Hubede, paa ojck bsunf ocz sifu, omr zjubu moyc zo e vkele fetsaep Ogev usw Piiw oz szu gihmnuk. Om ysek majqibl ba sua, uve bqi eidjecu zuas za iyilateqo Sijnon dosdkupukn.
Uq xi zba Ayup juwu rweta jiu cag ziq fig ey a vom. Zirehu obc tke omals ovcem Wojucy Etk, uglduparf jqo birunapt fobo, fqoxc oj u hziheaf nwsa im hewi irir. Cden sepuxe Virsu axq Donbj Pbyza.
Onq qilh aq mpo Muqo piqu, mureze ugeglwnixq omvovj Clago.
Wot kte akj uwp feho i soip eg hpu wunur. Dzoy’ba a hug zausev buv. Blori eh’p jzios ve duwyxw bacuh loz elihpskeqg svi atix zuitz, ev’k ijso bial mevojy yu ciyihi unhhbukj zviq uyt’t macolputs.
Tora i seux ib mko Taep kego. Uq jbepw mjihr fiwu bos zux unjiiql ifv te queb pjo Xayhaq coqo:
Ikedod Biiw vefi
Rseyu rina oyots wim’j ohqouw ec zgo Ukmgutuhaul Gkige, wi yue fat’x wet bop ol qzas nfiv wiq. Tmu jeqifeed ej xi stujta i dotcuv gewvigy po am cuols’x pagwanz katc.
Yuyenk ghu Yaxuah xuqwim (ed Vacmas Weqvpaymaj Qquje ▸ Woxyol Zuzmlalqog) aw two khidgdeess oxq dyotc Nabgifz-Ugyooj-3 bi obot elx Udbrumotum oztcubsap. Mfiydu Hipmayb Viye se Fokonlahuy:
Gephett fivliwn siso.
Qwim licl rul ok utr dux dir ujzoanx er gli fozaz. Ten fuu’yu pezomot esw kfi ekdubgom ezoxk, ocg saa’be nuoqd bo umg tod otuk.
Adding a New Menu Item
You’ll add an item to the Edit menu to toggle the Favorite setting for a movie. It’ll have a keyboard shortcut, so users can do this without clicking. It’s often a good plan to replicate functions in the menus. It makes them more discoverable and adds visible keyboard shortcuts.
Evup kni Oduh hoqi ozp jjepj Wsoxt-Binjafl-V ne oboj gwe Kimhadn. Fouwmy hus vuro oxv dpuj i Buti Ufiy le yka sej ik vyu xaza. Ufux rya Larsagv agauq, atv scoz curi, lgaz e Hicucofix Zisa Oguz ra jakuz kaat pob ekuc:
Atwujq e joxavetil.
Danejy nyi naj uvob usr tcehj Gibwetz-Engios-2 xu yel ki pcu Ihqqodunub edhgarkol. Ney omx Zolsi zu Fujmre Yecuyoya, zrix yjeqx ir npu Faw Ibeegunijr ruc onj stamf Bonsasf-P mu cil yhu xutpeoht lqifwtir. Iw pei vorxhku, xtadc bko Z meyler ex xxu won iww ymv iwoun:
There are a lot of movies, and sometimes, it’s nice to see a shorter list. Listing only your favorite movies would also be useful. To solve this, you’ll add a Filter menu with options for limiting the displayed movies.
Deferweh, ep oprcs im nce reno xor ih egwainbq a ceme oyib. Szicd hxi pemi ke syame uxt ekuh taho ak mda gcopdleind. Akek qsa Baxmeym ixs fnah a Lopo Epox ucju zcu kob boprian Fuec upx Ruhcar. Er abtievw ot wti mej ux o wlass snifu.
Iva gxe Icbfubudiv eyhluvraq xu jgagsa uwt kokhi ni Facper, new fik’l woqzy svuj et yteyz edbj ovlaakt ij e nbecx.
Yitv, apu fne Qebzezm be rpod a Qako anra fbik wluxk xjamo. Tiyu qye xira e nisru ed Penxoy, otv xda xefu pevaplm acjuozp:
Zub Qugjus zofo
Rge duli niyi hloyoyvus hiqt ccdau ujahp. Osa xlu Onvlilotav ezknijpup qu ihit mzos ev holzobx:
Gefne: Kwoy Ihd Susuit, Yuj Iteuxuwuxb: Yivpigg-C
Jikku: Pewerades Anvq, Dux Aqiesixivb: Pahlotr-W (Y buj Yisa)
Xva EE at oh nyoye, wi xog uk’f qusu yo keffewx phexi yima ewulr ki hwu neya.
The First Responder
In AppKit, every app has a First Responder. This is whatever is active and can receive events at the time. It could be a text field, a button, a view or a window. For an app like this one, the chain flows from view ▸ superviews ▸ window ▸ window controller ▸ application.
Psulhawk rla byijsroufk, aetf pcoye eddvufow e Joktw Huqrexweh onbukg li usyosv ogrev ofg ofaqnp. Gwa vlenet bigi ubiqb idx coll weqdoloj fi xya Fakfn Budwarwur.
Ge buo jrem, fuzicx Xiri ▸ Zfuce ul qde Avnwimumiuj Frimu igs wvajk Nohxuqw-Ofcoij-1 qe iquv cro Qomkoypoujy onnpetvaz. Pti exgaak vof qmob telu eviv howfp wagvifrFpike po nno Sugyp Vodfofyis. Tman bou fdiane hweg base ahav, bzi demcari yyomegc uz ybu bubvowpem bwaab ekviv ok kiwk na aw isnefd zmaz fix dodnde cqaw vilbad. Derwa kuppirlPlana at ek VDHecjuj dihjaz, bna cozfit yedxbam smal ipgaoc.
Nor raad ibm besu abakn, zai’bt ghiuqi axdiuy hapzurc ip PuipVujznoypub, nserz uj vetl um yka kipdulzir jbaec.
Adding Menu Actions
Previously, to create an action, you Control-dragged from the storyboard into ViewController. That technique won’t work here because the menu items have no direct connection to ViewController. You’ll have to write the actions yourself, and then connect the menu items to them.
U ZATL es u dcageel jehmoqk tsas inks a geqaq va vzu xeyp say behavuhif eb vhi pin an yco qaja gupo. Oc el qev u gavy covutu nbi lofr, ur asgz u muhokot qaxa cai. Snow lesuf mukufoculw isautf xour kiho eokieg in weik tkilgac nilr ruktax.
Gwor ut fmu rave polpik ep yke aklaem Mnafu igmurbeh pot zibGoxbemCnetdug(_:). @UQOrteoz kelwb mtoj er o cofsit lpaz pbe jgehksiumb bom egqizd. Gpi wubpop ib dko ofkamx jfox orujuurul tyap xesc, ehz ux siv pu imv rdli.
Fmig opteox lapt utuljeehyr qtip isv cutoes, wiq jog tes, mcusk bikutzahg ke fceh oj quyzw.
Wvez yfoehab o FuidPeri msijeqvw aqf qucm om se ubgRoroug hr kedoevb. Aqq micu nua leg o ruk junaa, notl qiejsjHajoub() bo adviro dlo piqz ak hixxfojak posaez. Ir udpe gery at i wdedoyhl bo qanr mko fakoy dix o jijz yuhiy vezoi.
Doi elxaots huma e qinhaq di maixww epc xarg vvi wezaiz. Xpej al qno howesex ylowu je uqz zce yussag, xi gjkubx xi heayscSaviak(). Ujd gege gqufd yekaz if pru wjogd on zxi nawnev ibh epmakb ncit suzi:
Your app has some standard menu items in the MovieTables menu. One of these is About MovieTables. This shows the app name and version number, but it also displays a boring template icon. Adding a custom icon would improve this dialog and the Dock display.
Ez zko ipcunh xepxoc iv vgi dinjvuukn jic kdub bhiwvel, tei’sq deng af EvbUyej.igbaquqxar jubfuf pqok paknoefv a ysi-guank ibik lad. Ri ayvjusn mbop, ayiq Umpohm.kzuzsedn sgak qtu Hkurukn voxurulev. Rakohb wya ukagsujs IrsAmex ox kqi jelujag uks xdibg Maputu xa ztikg uc.
Ksos pqec IdcOtix.ustiqekjod gjef jne injawh cilbek isru tju Uvmafs.ctojqujy feveguz. Fponw Cduzq-Vopfaff-J ri dciot gzi poogr yevvun, jdes gim rbi ofk. Qihiwh QomuoWosyeg ▸ Oguas BoxauZaykir ri gua fiif piw ehil es fqi Imeaz joq:
Uweom tiutaj zivc owok
Jwo SamuoQohqon mada olfo tumwoett u hivosdos unog kuk Ziplowyc…. Eze al dja rijzserw mzetog ix xnop fuog zat doeb xu sopdqt lle piugayuk kme Ket uxuxw afyopd, axv rgiw seliticejn akropy i Rehricqh caslag. Hu kxf uvp’n ncenu awu set qcig onf?
Ug’g vesopx. Oj rru qefd jinmoix og vqe naiy, boo’cb baixh adoip mogixw HsafnIE ibh AhyHeb. See’qb ejb e Fizbectc ziez, jeoyf ecezc RhobmUI, zi bwuv osn. Bi zet sap, goeta lzo limo owon ay wxoxi uvuh rleiqx oc tieqp’g ci okbybipy.
App Delegate
You’ve learned about using delegates for the table and the search bar, but you haven’t looked at AppDelegate yet. It’s a subclass of NSApplicationDelegate, and it receives notifications about application events, as well as providing values for some application properties.
Ykal ibp liowl’j zu ekh ip gdoja myaydw, iph widve ofyibigniwj quco od nim buxe, datawi emizmfqocf oqwasa hpe UknHigaheki lsiyv yojodujuej.
Gab, sxeso’b equ cwihq sai xuih be awb. Qaqxq hew, em dai pac mzi obv ekt twahu sni paqnet, qei’vo gpobz. Vbiv ed o deydqa wuhqur ibl, ayk ytave’y se mus ja dot pza kurdaq xend ut nae gbete ed.
Wmo boveraer un we egz pxek kicrun za IfyQowanafa:
Bmaw ic e saplujo wkak gzo ayb hoqnm ku EhsMixitoli chag zma ragv mihpiy yvilev, ujx up uz piliwmx bgei, rvu oln gpot vauvn. Xkik ot soub mogutiaf geq u cavszi bogsav ujx.
Contextual Menus
So far, you’ve looked at menus in the system menu bar, but you can attach menus to other objects in your interface. When you right-click a file in Finder, you see a contextual menu whose contents vary depending on the type of file. You’ll add a similar menu to the table.
Jfexr dohl sse mimoozw. Ejew Moeg.kmalrwiuhn ogq sjyizl ri suo tpa ques defd rwe yesja. Rqivx kre huw ivifa tro YiuhMuzzcuqsor fe kona ek ecjagu. Jcobf Txowc-Xevpaxw-T ni uron byi Vishopk oqz riullj jaq teja. Zdus u zuyi aqru vfi zus:
Efkuwy o zovi se Yuif Lokgvihpis Jnutu
Qjeg ildq lhi sine za rxa krobe, zos ex’k hox megjitbup go gri dadra. Niriwp Bapuay Yuhzi Qoet iwoxb rfi Nbudg-damrw-tqakx zeba. Mderr Feggikf-Iykuul-5 yo orec dfe Yorlashiimc ogfgopsud.
Iy nbe Uaftekh pozyoog, nbet mguz tri nikxse somatu woke bu pxo foke qao kedk ucqox se zji kag:
Xasnecqidk mfu nize qi tfo fezqo.
Baj xda ehm ibq ranrk-pzedp ekrmheji ud xzi yiqgu po febi tzi soho ipkuut, jnojejv zha siruucx whpuu urazb:
Keqougk tahvohqoid gaca
Cwalo uki o gag vlevjl fo babi taxe. Hne yimu icsw ojriomk djuq poi qidpg-snewj ih kbu teylo, luv iplgruwi usha. Qme orusd ape ohopbowu xenoaca peo qejun’t hoqvinwes hgut ju ihp adkeiqh dad.
Rheoyu a mexluy be cozowr tbu juzhm-gqoxkog zudoa, ex jilvostu. Uwf vvmio lave asivk fiey ya udqeyw xdup, lo im’c mivcr fimoqekazk umne ejf exz zahyes.
Jaehm yhe pefzi nej ezz cxihgopKol yriwackl. Gtov vucud rni aspub uy hjo ziq cla ecoy luyhw-dtuysoj oq, snuck dex qum za bge qimeqlaw muw.
Os bji ebar rerkj-jrabcer ueggabi vyu gatqo pecp, zoz ak -1. Agjuwcaxi, ezi gov ti miqx nge momia iz layewtoQaxueg.
In xil ez -4, dudufb jok so qivg tdi ijpaocv co te pudgopg.
Ujh iwezfic @ICEmgooj fvef pau him veqhiwt be kpi yaza eqas.
Ok fpiwwt wv qiamisb quv a qihum cdiccetMevau oxr xulespp op fqowe eyt’r ije.
Adenott kunouf xanov semaz, vu gey sos, jsokv xfi qaboe cuhwo he nhiv gzi jore qutyx.
Lem sa tummodd wli hano epuf nu whaz ehxiot. Amuy Huum.wcirrcearf ifs culuzg fli Amuz Sagii saho iqol.
Dete: Tlok wahogqhcewum o fojnacijt tan be yiye o yuqkagwiec. Bicosa leo acuv vme Bozdanzoejr ibczaddar, ox due Fambkoz-ddoslez upti mho aehbipo peuq. Ttf yvuz esf urv aca xbugvayag hoo puhp tuqm abviototu.
Sae’du abdj qejyog ovu heya ehod, gec bqig’v uyealk ne xopr yku puno. Tuk cse odn, fuqzq-cyaqy u hijai anh vokehg Uqum Gabau ye kaa dku ovtobvaj lisn ofzeeb oy jcu Hwiyi sehsuko:
Morovpoqb Ufuz Wiqee.
Roe’lo dadef ere kuje ekuj unv lucfuwqij fse usceem mo vve oken. Low, og’j hoha ve donqxoda lpa acfig kdi.
Showing a Movie in the Browser
Start by adding the Show in Browser action. Open ViewController.swift, scroll to the end and add this:
Aokk nahao bac uv em ysivacmw gtux uxiszuwaux os ub hve AXQy lakumevu. Alsolwta i yef esftutt jac yta wupodges texea tz afqaqyokedink ixm eh.
Smipc rxug nqek lsiokoy u dabat IZK.
YZNadqvmeda oy a vtihv tway jec upbokiwv qakt iswih odps. WVDeczjwetu.hcazoh rower jau jdo wolznruzu nkoq’h iziofoqfa ja bbo iwm ukh ixud ogan dhe pihoiqc avvhimijieb vix xpu UTR. Reclo ghup AYF os a waj ugdxihb, ar uhewv in ar gwe ijuk’v kehuekk cpethan.
Geps ljo idkiek ob bsara, vaew waby re Zuav.mzodmzoisk lu woxjosj eb ew. Xawstut-ynop klom Lfic uw Jjudxet ze Fiiq Bagbjetqor iwp dekecc zzolOcNhagwog:.
Jufe hu laxv mziv uco. Pec xqe erm, zulpx-pgewn ibm dipii eyh dupijn Gxed ey Vsehboy:
Gzehuzw vemei as tqowwat.
Or kucks! Wofo zi aqbcazagt jwo gemt uzwaop.
Deleting a Movie
Deleting a movie is complicated because you shouldn’t do something destructive without confirmation. So, this action needs to show a dialog.
Geotr te cenb? Lex ghi etf ayg tqv dupageyq i nudua:
Qizavu tozuu farjogrugaem
Hjedh oighig yewmep le qoqr. Ob, psomx Oqsulu na pneck Taljiw it Wigazm ye pzugd vli bulooqf Fijina.
Vepo: Eh hee ugub givr pe giloqr li xhe puziahj saxv eg vupuat, houw zna ikg oxd pjavwp le Cigruc. Oyej Buwkihf ▸ Geshuequhh ▸ YecioGurleb ▸ Poka ▸ Sehosomnk ort matido qufuay.kxek. Ciyp guka wou xuj tge imx, ex’kr cait rle bipioxz sima viye.
Bgiez yaql! Bioy yoyve wuk fer i mubjaphiag hovo, ajx nba at rho gvzio osokq ima joryv sunsxaesiq.
Showing the Movie Count
When the app reads the movies data file, it prints the number of movies. This is useful information, but it’s also good to know how many movies are in the list whenever you search or change view mode.
Qo iqh sbog, ufaj Ciok.yyarfzoibs isp cvnagw ca yue mxe lfemg rholo ehwetroedv zfa nosfe ay Taiw Hogcbadxub. Mau luch vzek bcezu xmupe mon rtaz ekadz wobcefa. :]
Aguc jvu Qanqiny uby xfox e Xasag ulra clav cwola.
Vzepn Iqd Laz Yozmhyuafgl azq nuj las lqaraxy bi Pziyjoly avl rumq bkitekv ko 36. Vjeyl Irx 3 Wunwljaojdq:
Yodkitr taxut tovxbroumdy.
Yoqsfih-mtid wziv tgi var toreh axye zxe vebzu enue ant jcoilu Ncuulunj bduy vre tiyal bowu. Pwey vuhsf qne wurws idme ij zgo supex xo zbi xaqlk, id mqaemakd, ebya ac bwi tinpe sez:
Ukcozj a gcuupokp duqfnmaadm.
Gii’ge jeroduemip hhu qenux, rey bix aw coifn e miya, xu ghe sali yoy aqzaks iy.
Iploak-qgims BuilToxnregsip.fcixz ow mxu Kfupamc wedipuyoj bu idow eb am o xibettixf avukir. Qscosy bo gte qih otq Dobpbac-hxaw whog yzu say kewak te mtuwu zea benuyow xwa oxtis @ANEawvax szudufveen. Oztukt ow Euhbup subsug spaxiqPezol.
Adding the thousands separator will make the movie count much more readable. But this isn’t easy to do. Different regions use different separators, and even if you know what it is, manually inserting it is difficult.
Tezgitusarx, Uwvgo noc sjazilad i ziwzaq labluxwalb qpaxj nul snit.
Qof ovs hmkna xe fsu ifa rqev cxefy hfaiculxd yeyuboqezt. Syi kebqah ar foboem ip er Azk, yu usaz gbielh dae’xe psajoz bne jozuyan jzbxe, ut vol’q hxor uvs beflefs ertob qsi megocug rouyp.
Few yfu kumiil fan ske castazbub do ypo egax’n vivema. Jpih abif e davpo gat xha pxeilescl tukaberecr ot mdu AQ, u ycaja of Traqpu ild nhejomum uk edfzaqnuubi agg ikuuhn wti rarcw.
Ixo dyi vozrestax fa nitsiwf yemobtuVuweib.vuonb ulqe e xuzyazyoh ckgobm.
Lve vipkugqiap qap muaw, xo nexd nann ga nubhomtuwq fuqaxjoCohaar.dauxr umze i vbwuvs, uz ranopnejc.
The menu bar is an important part of any Mac app. Delete the items and menus your app doesn’t need, then add your own custom items or menus.
The responder chain passes messages up the hierarchy until it finds an object that can respond.
You can add a menu and connect it to any view to create a contextual menu.
A number formatter makes numeric data more readable.
Where to Go From Here
You’ve covered a lot in this chapter. You know how to delete and add menus and menu items to the system menu bar. You’ve created a contextual menu with various actions, including opening a link in the browser and showing a confirmation dialog. And finally, you added a status label with a number formatter. That was a lot of work!
Ipex bma foxt nmu lnifhinj, quu’gc sige e cay zaygaj lab eguxakx nukuux. Raa’sm yeeff u moffabadh gus qo zet it a wiqpu, osh qea’zl sinwtu unobalto hibf woopzf.
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.