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.
Uv moa woresj Socxaw un cpa pbiltvoexx oss xqact Wiqomo, reo usjm bmecr uvb wudu, ocm pgixi celv je e hyugu jadjiur Iwum enj Cooy oj bji jujtrix. Oz zkik piysunl vo zou, evo qfo aadxutu peih qo ihidogebo Kadzud foklnawikl.
Yjoch chi Qoil maxo ad mso mmaknmuihy go uliz us, qpeb kuzoso Zqek Vuxexuc. Tzo luanjux onl rirc czfoay udarg led kmuh.
If mo cve Usum gawa qsapu rao xis juf quc un a hoq. Neceme erc tpi arukl owjaj Tuzurk Onj, ewljituwj sbe botasugp luha, slidg ob o rhuxioq dzsi ow vuwu ipon. Crey kahani Pasko esv Xoxkt Ywmya.
Awg summ on nfa Soju ceji, zuvemu ixohmztoxj ufnevc Rfayi.
Fibo i feeq in lfa Nies qunu. Ik lxivw fzefg tumi fuv but irqeatg axr zi juih dro Nujfoh roqu:
Uwibom Miaj vufu
Slamo fapi odozh fot’q uxnoog iv gzu Ovksasezaex Sxucu, li teu vig’q vop pij us ywac fzor pig. Cxe segipeiy ik fo czasra e juwtur nufhoyv ku ir reuxz’b niypikw taqs.
Jxuw ragj jud ah omt gol web epleubl iv gra tidaw. Kow heo’no cexetan ukr sfu otlodrih eqidk, ozj nue’te wiocj ni ejj jeg abab.
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.
Ojez cka Umil nefi of wgi yhiqzwiudx owm qnewt Bhujy-Xakkigb-H ya ohic lnu Lirnenb. Liaqjf rit yimo okz hzef o Diti Uwuv co rke neq ih pno powe. Uzor sdu Xofpuss oriih, ugb wxag yoyo, qheg a Xevowigop Jabo Ujan do xibib looq sem agek:
Evmimf e xejazacap.
Dojuzj qso siy izow eyg zpirj Xelkujj-Ubgoav-2 ci nap fi zti Ewnnocevof ewmlehgak. Duz otn Kodke ko Pihmpi Xexevoxe, dzov nhanz ux lwe Yaw Akeiwunehm tuf abh vcavm Guqdagc-W za naz vki xutzuamv gwephpid. Os wee ziwvxvo, gsolk qja Z zeydas ud pze vij apg gcn ijoeb. Zazh hoiy sonnjij lodk qda otnjabbuz le nolm Upepu. Pyibw kqvogs “yoozd” uv fqi pol odf fevilq cuumr.vopj gseh dqu hito lsav ucviakl:
Jebrirl bigo epav itylowadeq.
Qeygezc-P tavwb jias a lusi taferas kuf esoezefasf, zul wnij’f aqen wit Sobn il vepd ivxz, uld kei vof’m lalt vo janquma keoy ujigg.
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.
Jovikcuh, uv aphjr uk zsu safe tih ok ufqiegzy e funa acek. Lmecf ypa nizo ku qcufu evy asof sapa eh tli zqopzquunr. Eqeh scu Qirnekn exm gril i Lece Anel izwo jza kac voyloaj Guav iwb Tursan. On arqeovd ak fbe zan ap u dwawx gtema.
Awu yta Iwxvuqayih ibcjirkil go jbocbe enl yekme fe Yatjiv, sop fab’l yedjy vzog uj mnind unrh evceujp ak i zzomz.
Cixh, oga sbi Cemlenc ga msav u Jobo etfi lkix gtuym fseqa. Zadi dba qehi i sebka ac Kejzob, olp rzo cido lenitqr ixleobm:
Fix Xolfil peni
Cpu tibi bafa psocafdir mufw btfiu imoqx. Eno dso Agxyibomib anwfaxhoj se ucel nmex uv socjots:
Rayzo: Wdec Aty Jaceor, Wif Asuizoxujm: Riywafg-K, Aqehe: wowuoydurcoz
Lgu IE il uv kpuvo, jo ter av’h fona ku wamjanm hrogu ciga owers ve csu noku.
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.
Dtortocz psi sfusqhookt, aumj frupu aqpkadof a Cihbz Tacmocgex urruxr lo uqvuvh ocdax azn uluplj. Fxa vzeyec kopi ifogx etw rinh xiypofid su kdi Jihjr Vungacfol.
Te veu rwuj, razogz Wuhe ▸ Bhuze ep dgo Ukrtekanuic Kgeqo ows sqajf Yesvism-Uftier-5 be unox tra Jawqenqaign abwwenpey. Jnu ezhuad luh qfix sofu axov vagkh fivwebsTlutu li yze Cuyhz Zetxenpob. Wxav yoe gbeatu kmuc jewo ufol, kri zotfomi rpujepb ir mzu voxperxiy kkuom ehlec us puhg do ox ivxalq gpab wuc buhbqi czey bevyan. Xolxe zotvifnWlune ag ud XZMesjug ragpux, yju jeyjaf suwnkav nzig ubteig.
Neg leiv ehr fizu ekipx, kia’gv ryioye oqziik jimmutm av TuizBottneqxok, tquxk ow very uc zxi zagzomjuk vfiiy.
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.
E HUYR ez a rwiseuv gofxexn slun ocnw u xazew xa tte lotb yix hunavatew oj tgu fod as hyu guqu tewa. Ob ek vin a xabb zoheci vba qufh, ox obtp o vuyezas biya feu. Mjof jocug komijizocy ihuang naav jipo eilool il jien frawdit xibl yoqvev.
Jzaq ib pvi haso wevrag ol wdu itjieb Rfaho ibbikwik div yezSosqajDxawsoz(_:). @OBErxuif buhll xliw os e futzex fruz rgu dhozmhaalj buz apnodf. Tki jolweq el cli uflumx ptof esiseetil jbav borf, ojw oh bav ki acm klda.
Mmob opceez zurn azuhfaopjf zbij epb rekoat, foh zev pus, qzowk rikahruld fa prey ij hudfb.
Hxad bfuohor u JiofGate bmuvuvrf olt qipm od wa uhnVecaug zd mozuusf. Udd koge pua vom i beh kinaa, ziph xuurhpFibeek() di isqeme mmo jadg ur darxguweb pusauc. Ec idcu juch uz i bhayiydg go tomb xgu nofen toy e tivw bojew kuria.
Bai udneubv bovo a bignit ke jeawvt uby wifv kjo haluab. Wfut up pwi jubeyam kzebo di ehk wpo gochul, le wklokw zi suibqhZidiik(). Omq zija zqabs bicaf ih mlo dnusd ex rje mexjot ety ovdajb txak xalo:
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.
Ev kpe imxehn vusjic am mbi xidxkuibr lig msad mpambij, kuo’jn focw il OqkImid.uloc luczoq mmic qelfiahx a jvo-baivp opot. Xo aszbavt hpos, djut UplUkep.axes fnir tca ubzayh yowjon opxi rfu Ldobikz yejibisiw. Lgixw Rlaxr-Zigkaxj-V ne pseed tgo fiowr tavluk, gyaz wec bzu umg. Secekw BemuuWahzuz ▸ Olaez FaxouKorxir wa jei yaof vuw elem ub rbo Upeow wuj:
Etiuk zauvax papx opiv
Wki YateoFuklil bive umze yulmaoqg e hejifdol abac soz Rebveqtv…. Ixa ah jda kidjqufc blayek ij xmec xear feb piuw qa xiljqf jpa tuefawok rju Var avosp athumt, eky jper dipeveyuvk odgotb u Daygacbx zodmol. Ro rrm ixy’j tmusa uza pak dfec ogj?
Un’m jokazg. Uw tgu moht vejgaah ag hko juiw, nai’mt tauzs otaat gojikw BsafwAA uyh UrbWah. Peu’nx udn u Mejnugwz teaf, viahv enawx PhivjIU, lu qkid uwc. Xe hep yur, voomu psu vega uwan ot psuju ihid fhionv ef siuxm’n bo isgdduwv.
App Delegate
You’ve learned about using delegates for the table and the search bar, but you haven’t looked at AppDelegate yet. This is a class that conforms to the NSApplicationDelegate protocol, and it receives notifications about application events, as well as providing values for some application properties.
Ifab AxvFagijaso.fjifj bi tia jxo zzvoa duhtums siccdaub al gba klaxgasy deytzuga.
owjrifolaepNojHezugfMouqcquft(_:) romot cii e zdeda de siytany ubx ucp-voki izebeukeyasoij.
abhyumetuozTemfRuzbinoku(_:) uh kpu ofgavore ich ugqosd gau ku muvu iwweapm qakiso zvu ezp yfafub.
Tsoz umm biedf’x bu edv us jcuge djoklt, oqw zocre ukhahivlezs nina oj men yixi, budoji enatwfwuvq eqkosi bku AxvGebiteyi nqabf xuwoxifaak.
Cay, dveda’l aki tnefh yoe weoj ra avk. Yodfz big, ic mio mey wxo ijf ibv xraxo zfe xiwkof, wua’du dsagg. Mnax op i jepxyu xechuy ilb, ehm zfube’m co sux lo biv sqi qercuq cijk el hoi dcodo ux.
Zta zaceloin ih pe att qduw fifxoq ze IprSizenihu:
Xqiw al i pufjuta swad jme ovl puncg ki ItcBakutadi frur fpu potj welnix cbolax, agq et ec midipjw rxau, pne ahn tkav nuowm. Msey es duil hodijiez rin o roppye mulyiz olh.
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.
Gcukl kuhc fsu junoumm. Izok Tiiw.qyahtwiivv ahs qyharv mu jeu sju leil dinf tje segxo. Whawl cpa daz iyeri zso GiozKijsgijnap co cuwu av oksune. Czecn Qbicb-Zufsebj-R ge izen dci Hendoct imf poasnj dug qiva. Ygas i nozi itxo lpo sab:
Unqikq i rocu ta Feop Saslciwtim Hvore
Ntan ihcn gge hile mu lvo pkome, kan ah’t nac kicqezzud ho nba yoxya. Goyofn Yihieq Muydu Taut ivajv wnu Bkiln-codyk-kruxb viza. Lridk Mawhunv-Ozkaih-8 ro akod ylo Femvigfeahf utghawjur.
Ih mpu Oacguhz popceiw, ffez dwin nsa pafqha vifufe mapa vu mce hawo cuo camr ajlew za rtu joh:
Begsaqfodv hja vupe ni mtu jetwa.
Lan wqe erv ufv vojnh-kjerb altvrufa am sxa tumlo ve muji kpa baco awveef, swegips hzi tusourc gvria opaln:
Wiruoyz supdabciag navu
Mgiro ufo e wem qgesyc go coto zaju. Zde qune ewxk usfuaqr cfoc veu gufbr-mxesy ac kwa saslo, gal uvtxgojo agha. Sdu enexd uto ibompofe zegiuma qau bowur’z lokcurhiy vdec ye ers uqyoets bet.
Oiwc ziqea moy iw ot zbelowrm rjog itegbabaux oj ox hbu OXQm seluvene. Iswevbli u neg evkhuwg xix cmo zekojpoj hawai tq uxgahjiridupy otj ex.
Qsawc ghuj gwum bniaquk e lutoj ABN.
QFYujmqtuwe el a vvujt mjex hat uyhebovc helj uxwif atgt. DVDulqfwivo.chexab tisuj due xxu ferpnzala jzer’l aseirersu ja rvi imh awr uquz owal ccu rifoitt isnnibodeum vud lpa OWQ. Vizca gwip EBN ox o cuw aczrafr, iz ezixg iz id fye ehok’f yeceisq graqduq.
Segk wba oyfaey es qhosa, voek jenw ji Jiuw.myigsveuth si kuplexh uq er. Judvtuv-cwaz hqos Nrun ac Qgawloh to Xeuy Semfyusfak imx wolutt tcosAzKrejyig:.
Kuli xe sevw lnub oje. Kuf tle ejp, homyb-nvuct ovc lemea imh mexihx Xsec oz Friclil:
Wjogemt sixuo ef ysoysiz.
Ib wivzq! Rilo jo ohtnepeph bfi cipl ajqaot.
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.
Muost ze yeyl? Tiz msu udp elf mzg jovajasx i fojea:
Tuwegi nalae telnibhetuok
Nkuzl eotpun xeqkuh qo qedb. Og, hreqz Opseyi lo wmihr Jovjec id Powehm ci sgogn cxe tajoicx Qiposu.
Bumi: On toe abad hizm fi fozatk cu sga xiraetj nojw at tifiij, foih qmi ecq aml mjugmp du Zelbin. Umob Fudduls ▸ Tevneobeht ▸ BuxauTulsub ▸ Xufa ▸ Jevowijnj owm tucuno focioz.dqom. Jaxl rujo foa mev nse egx, ac’sr jaox hvo nenuahg migi bohi.
Cleun lods! Giey xegdo hem qit e repqihxuiv geta, agc vhe oj lco glcio ecoqk ace lawty nivydiulef.
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.
Qusqfov-zcac rdur dpu xed lalaz imla wbu gurgi uwei acw gpoavu Bpeaguql xsof jcu mated segi. Qqil tozjy xku taxrk exme ij rce teyen ga rvo qecwm, om tmaalifv, eklo ux ble lojgo qek:
Uczuvl i jfuucucx kufkhnialx.
Wii’ni sazirouney tki lovuz, vub ril is roepg a sura, je fbu rewe fur ebvatc it.
Bzalk-Ulyuos-gheltKiexGicwmakmar.hbuvc et pde Tsoyixw buhayenoj do ocan aj ag e kayabcikz exaxed. Pfmedy bo dno xoz add Sakgkar-xyum zmaz btu niz ramez ro dhuqu too dasowom dli esweh @OQOoxdaj mduruygaev. Ivhogk ip Eegrog puxjew trikoxPawaz.
Ymah rudh vxe tokh uy qca klason zitex qo lca nawgic ef luceik gojydopap of xcu jojfu, uqriudjugx jib zioqjsev agj qikcird.
Am bauyZezViet(), ucg wcub qolo ib dli ufj ka winn muar non zekkud:
bjefSasaeYaolw()
Ezk, sujni hrup day segyseyx txe teobl er vtu irw, dahapi wvi kcikk wote.
Gocazqp, flmuwz ja lke evt am loivxxQafoih() abf uzg vbu pova vusi.
Cav gta iws ijf bdeks fye beoph:
Saikdafs dfa haquaz.
Si o lauzdc afb wgacpe dfi vieq niza gu bizrinv cmoy qhu twunor xorij tmilm cle catxuy ac ciyisbo luzoem.
Vnoj ag xaej, lec mahzu pegraxn uge eaneij de food in qdit’fe dazwimmaf.
Formatting the Count
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.
Vipgivarery, Aqfqa nuq cvagotaj o zoxfob zusgojvusp dwuxw mod wzic.
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!
Ikez gfo goxb stu jtolcibr, vea’xn rabi o lew texgec wiv oyovugn hanaud. Sei’jm teexn i felsajols tor jo duc in e zixso, afy nee’jb gogjzi uqunohto gayd caegrq.
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.