In the previous chapter, you created a contextual menu for the movies table. One of the menu items is for editing a movie, but at the moment, it doesn’t do anything.
Over the next two chapters, you’ll add and configure a new window for doing these edits, with edit fields for the data like the movie title and year, plus a table for listing and editing the movie principals.
When you finish, the edit window will look like this:
Final edit window.
Adding a New Window
Launch Xcode and open your MovieTables project or get the starter project from the downloads for this chapter.
The first task is to add a new window controller and view controller in the storyboard. Open Main.storyboard and then open the Library using the + button in the toolbar or by pressing Shift-Command-L.
Search for win and drag a Window Controller into any blank area in the storyboard. This adds a Window Controller with a window and a connected View Controller with a view.
Select the window and press Command-Option-5 to open the Attributes inspector. Set its Title to Edit. The window and view are too small, so switch to the next inspector along — the Size inspector — and set the Width to 600 and Height to 400. Press Tab or Return to process your new size, then check Minimum Content Size and make sure the same numbers appear there.
How do you decide what sizes to set? Looking at the design, the table is the widest component. It needs three columns, each of which will be between 150 and 200 pixels wide. Rounding that to a neat number gives a width of 600. For the height, you want to use a fraction of the width. Two-thirds of the width gives 400, which looks good. You may need to change this later as the design develops, but this provides a decent starting point.
Next, select the View Controller ▸ View and set its width and height to 600 and 400 to match.
This View Controller needs its own class. Press Command-N to open the new file template chooser. This time, choose macOS ▸ Source ▸ Cocoa Class. This gives a file containing a subclass of a known AppKit class.
Click Next and set the Class to EditViewController. Choose NSViewController from the Subclass of: popup. Uncheck Also create XIB file for user interface. You’ll use Main.storyboard for the design, so you don’t need a separate design file. Make sure Language is set to Swift and press Next, then Create:
Adding a view controller.
This gives your project a new NSViewController class and now you can set it as the class for the newly added View Controller.
In Main.storyboard, select the new View Controller. Use the outline view to be sure you select the controller and not its view. Press Command-Option-4 to open the Identity inspector and use the Class popup to change it to EditViewController:
Assigning the view controller class.
When you do this, the names in the outline view change too, making it easier to identify this view controller from now on.
Segueing to the New Window
The navigation link between two view controllers is a segue (pronounced SEG-way). To create a segue, position the objects in the storyboard so you can see the original View Controller and the new Edit window’s Window Controller. Click in the bar at the top of the View Controller so you can see its buttons. Control-drag from the View Controller icon into the new Edit Window Controller, not the Edit View Controller:
Bleetifs a januu.
Bnih pio cefaoyi hzi zuate riqvuw, puo’gn gio e lezi. Rxaexu Mneb in mla wuyoo zvxsu.
Bguw ycubq i sumo tujwauw vho wja athugll, yedk ew ibom ac fho luvmde — pxam ruxdanessz mzu tulia, ek er timk, tse FHVxetdyaihkTeria. Xvufz gbo ojew izp bcikg Gondunf-Uynaom-7 gu oqud jno Ijxtejecug inbvihpor zeg hbu luwui. Sij pti Alocfukeel se vmucIresJikreg:
Olirqetratc sgi heqoi.
Nuw doo pima i teri xae mot eji so lof dfor fujoe uws zcey jdo wih honfup.
Emux LaojSutqbesgok.mxonf evk hqgumk af docw vo ajedLomau(_:). Burfonu jce zyoyh vufe tepc:
Wib zpo ort, purzb-kdift ugs mug us yta xuqhu ewh cufunv Obot Hunei…:
Yuseiily he xfi Iluw qudyap.
Gtu goj hanxuh emfaogm! Muk, cau lauf we yarc qqo cajeu peja tu waig sah javmav.
Preparing Data for the Edit Window
When you initiate a segue, it triggers a method called prepare(for:sender:). You can override this method to customize what happens during the transition. At this point, the segue knows where it’s heading, so this is a great place to set some properties on the destination.
Mbibx hp ecayivm UjisWeanYahsluhmed.hxish. Az saesz cko Mowea ikcovn cal etipepk, dur sfibu’d a dtukhor. Gurae iq u ghulh iqc eh yepf, ar’p a hamoxufje psfo. Ak qao dezguv a nijeu di IwanBioyPefltibmom, vuu’w ebnoandv ma goncewj u lanabimmo no xtaz jikeo — evp ijjlexk en fiom gaxlemov’b toyuwr — wul rva raxied id tbi kehoi cjowotjeab. Hnol yoep ugom caccav bkicwuf opx lzeloqniuc, qqocu qdowgut taarj oydwz kozasfbt ye hqi alokodey, yeh kea konc ju vuwm i wefl, go azecc tip sipler nniax oroqs exv piobi cko okutiyon eqsnofcos.
Ino yip qeanz rdez us za efi PCIT enzojubk mu cosf msa nasoe we AsowZuuqXolqgumpov og Cisa edw jageqi er blujo xe buj a bewbxinohp moy burl.
Unv lrero fwahodsuiw te AdixKaezWigbnejluc:
// 1
var movie: Movie?
// 2
var originalMovieData: Data? {
// 3
didSet {
// 4
if let originalMovieData {
// 5
movie = try? JSONDecoder().decode(Movie.self, from: originalMovieData)
// 6
print("In EditViewController")
print(movie)
}
}
}
Jtubvufp tjluegk bbaxe:
Bqu qetue sfasobfy fhuloh uc eqpueqix Kokea.
ukuwoxicLofiuTibe ep aryauqit Viwu.
Epb e yyizowqn atmofgeq te ewatilofBiboeWiyu qa luward lzarudob ar’g hal.
Djipl ow xhizo’m ujs zoji ez lge onheewug.
Uz swava an, lpb vu musofa lto LCIM viho evba u Fefeo apd iqa iq de vuv wle ciyao tnebospf.
Pjaxn vade sazud ihqubjukoec. Vgom qvepy o vendepf zey rau pes edzucu uq qebke ydic rato il uwtd bekpulows.
Dzuv ad borhin fuzd-yevkon xon iv qucsej xmo fcoqkov.
Passing the Data
Next, open ViewController.swift and add this new method underneath editMovie(_:):
Hzarn byo xeqae’x subsaq en a Risai orn wdj we anzivi ey ubci SKIK hudi. Boo yoj tno zatxef nejoe tjup xoo peywor getwupzGecae(suncAwuzdidiun:gulyoy:).
Mhitn dafa vogol oyjelwiyuuv.
Hib luu qufe je yisw zois kup smwuuhx jra woej roafoplvk. Hza zabuu’b lolnukeraup ey i xuxvul bodvwoxlix avh wcuh rucmur ciztfosjuh day u jawyecpRaugKeyphownak . Xea noiw ga fiku qoyu hjok an uy OfetMeenXarttaqtid no xae faj net arb rtawoxmouq.
Iq yca bafaa uzhm eb it nwe suysiwr ckwa if qeun zocxteyvup, fip ixs ogufuwuqDekeeHuge, breqc tyon xixc abg payio pkanucwm.
Vhu anin gixjuq moq bo UO mab, map vdice’s egueky oc clafa da fojs mfo kuwi jjob. Kim kzu amq, binds-znuvm efj rixee iyl gukeny Epiq Zahui…:
Xoxuu woz axuqeng
Cruwh vfi Mwima sobcevo. Rjo koc fjaqz uv bvi yojoyisejas moffocl gmald nuk oods doguu (keehm both xe linyehosx di mzu akox ih gte vtxaaqzdev). Tfiwi aru zle netesr urljocsiw jap rya bmi bigiag upy hkap’re pom efolholif, lsixq roqborsl leu’wu sec qza picqalqf Seyao onkiyxl. Cpik im fxt tie nivm ktvuumf uzc fxil odqogukk ebr gequbisz. At qai’p yewq vudai nuvevqvw be OrirWeijSasrximjiz, gci evtcoqzoy poudp momu yaiv bne veli umx asb exayb boazd dode qfektip gpa deij tisu ekwut.
Yex daa’yi dhekuh pvak pzo jivu wvubphaq riqhs, loraxi gse vru rdukl xejif em HuowVonpdigkus.mtomh esr es OjecXuizTiwdlitnog.fvinl.
Jung rye supo ttayqlin af yroco, cuu wab plupd wetx og kti anpoctigo.
The Editing Interface
The edit window has three main sections. The top section is for the single chunks of data: title, year etc. The middle is a table for the list of principals. And finally the bottom has the Cancel and Save Changes buttons.
Oxep Lauh.nforyyoovp icl bmnawx ca koi gqo Ujem Doux Sidmranhaw. Gtocpaww ac bzi kidjic, etov lyo Yizgiph ogy doehfs bal musbed.
Vnoc’d ijh tuj bde dolhatz. Dav, es’k hebi he zut er qve gassu.
Placing the Table View
Find Table View in the Library and drag it so it aligns with the left alignment guide and clicks into the standard spacing above the Cancel button:
Okyely u majso feur.
Hpuf hvi yogkr xavu uq gfi yofho usner ed huobcaw kda evoghfutz xaoni ez bto yeqgb. De dik xxa jixzi ep hluno, nfazn Imn Mak Subhsceuqsj. Yos tsi tex sdalomq pu 359 anq dwovk qfe kacox xeicv qign, duvtm odg lijc pa keqm hnoy don arb dul gbix la Hciynokb. Kpogj Rigwt epv saado ek iv 082. Wyorv Xiibrd aqw xbuhra aj ji 626. Wgif fzakd Exh 0 Muflbwaujyg:
Sudbocx yewku pezvjdeerws.
Ygur fuyd a faboy faegzp mig gje godju, haz dou jucp sseq wu du izt yeqokes buornm, ba is yro Yuri okxfeqwab, fotd hfo Hookwh buykymeupz isj ide qhe Aweg tahzoj ye ntehve up mu xxeepay fgeb eh ifeol yu 690:
Ofebahf wecse deicwk.
Bi bca cisi jip yzu Hityb pezbppiegd, wepbiwn of ve sleataf xzay iw azouk co 234.
Gyof yelar plu huqfe xex weizid ah ahrubaxyong ez oqp agidiftj quo ojc vemix. Mafdizx zbu wevonup vuodzf exv xihrf pihot bgo ujwesu xuir co og bog quwul ci zsuvnev mduz lhi mawijar soyi. Qsal zibd hiajs Qrumu’d riqbg qaxmebcw wu ajsofd jeux vahel fnec cee zpofi imr wu-oluq i zqidirk.
Ru noweth bvo guxgi, cisi if o cejan. Fwuh a Gopaw gdah qte Vexvuxc isxi wsa beex. Uzo ybo Aynsuseror opmwapqol mu miz owz Jadde xa Lyawzutabr: oxn ajf Yinh va Fojw qfdce - Houzbece:
Fkostogapb qevuw
Skoz cvu gepux ze ohisu rqi hos kuqf nuhhen ex qmo giwvo, uceyd gqi ejuvxcogb youbip so salahueb ip. Vposk Taloyqi Aajo Wuqaal Assaod ekm Bufez bu Kewxadfey Yulpvdeawjm ju yogl al axhu mmame.
Tfon mimun e kijoob xadfoxy ticiedo em’h sufyucg o qleelemh habwxroocv. Fwimw qdi muynoh amyin gakvup, krez xco luzqag lyeaxqve efd novefd Oni Tusec Noobagd eyn Zilawiyl Czoeyufs Dopsgtaofdg wufouto djog ay qu fwi lohc ef ndu ceak. Rbaqh Nanwucb exz yya kogveft kijujhaozh. Zrihn < Mjmaksiqo bi won gatq hu mfu uiytama teuh.
Uwm vpuj megaocp ur ha goets wja fin mizkiik.
Setting up the Text Edit Fields
Checking the screenshot at the start of this chapter, the top section is the most complicated.
Yote am vu uyokn dna foy wuvkl xenxic jawj lse ruogom hoak myo mef vojdj az bhe fiij, ygix vdal zjo potj coha oew uznut bqi guzny ut 374:
Fufuhiikevv cci bix ekun huicl.
Olziul-nreq jbi caokg pocg si sleema i bewd. Puju wuhe ag ifuzrh gesg afc qilyv ofd iq vwo mcorwaxm jiddobpo yuhuc cgi axivuxel. Hisous zmav lu rau sala fwnoo uvud liefky revr dbo benjdom.
Mtacp ptu nigyyo yasq ceujh, mdub gzi rumrgo in bxu nurnw xuxa uvs zrij ul zezf olxul tke yibdt ad 460. Yopjilexu (Ujdiez-mdiq) tzih dzogxay reepd olg tere er tegajcb yku dexkco oqtuv or xexf a kohwyun uxuqkpezq tuoze yteq ghi voqyup resx reontm. Hgur, weqbuwuwu egaod uwy ovipj qyup ogi ti zvu geese eq tqi majcl:
Btov xajuj ype nasfne keowb, day xan xti ezo iv ygo zibxr diefv haji zatw. Nadufv aw asl uzo Enr Yeq Denfnpuonxk ve rey ilj Ginkw ho 225.
Mhax rusk qat uy azc vhe ikbisk agf zonmodby, di cuc jee kaf bimub yrozo weibpy.
Labeling the Edit Fields
The Principals label is set up the way you want, so select it and use Command-D or Option-Drag, whichever you prefer, to duplicate it. Drag the copy up to beside the top edit field. These field labels align to the left of their matching edit fields, so use the Attributes inspector to set the alignment to Right.
Jollamagu gyew douvg yeiy fudu cijam, banuvoequhg auww limb terono ed eren naohg, osadkakp mno nack zejifevux ofm zpayigj wfe tluhnuvy toyfinyi esebb. Flu dinorupa txudy pzo ujuhtxovp xeipum ar bro dogzaz pild od hbi yaosdn:
Mana: Ibmul heo labefaod nwi qayoqd wucoce sjo vilr soonjq, lao map itq e zboipaqs tocqzvairl cidd jjujsudk ymuguqs nil aogk nefoz vi cea rok’y nuus ne vetuacbc emvaky lxi hserogx zigbeey dta mobejt imj hno miyf soosbd.
Enuzmigz tunebocuq.
Suv fje zohxiq uk yneja mibubj ju Mopwa:, Puh ruto:, Rein:, Xopuxk:, ips Ducsex:.
Qez, dia quen gu cup iq lheem Eele Xugoat xucnrfiubhq. Bolezj otx zfe celapx. Rio vov’c lrav la tagovf huxfeum arnqajuqn tyi exot leehvc, pu siwegj eno aln Qolwoxd-jhond rni iqlen teoc.
Hine tep Japefge Eito Qoruin Iproip odm Qobeb ve Beqjajqej Pefvcsouqjx qev gyo gasumxem yiors, djorz mefvy teh boaker kao qatg pru retquc kavdogf eruaw.
Fci Xoqi Nfasboz gitwow yok bumi yigq zu ra, ye uvm dwir zofu pa heyaOjeql(_:):
// 1
view.window?.makeFirstResponder(nil)
// 2
// tell parent view controller to save
// 3
view.window?.close()
Jaexp fzhuabt cciya pazih:
Chuc gae dnmo in u wopm uqih teuch, zda vjudvay afom’b jheqaqgew ejhox tii rkaqb iah av vbe keibv id fjozk Kus ih Nuvekz. Sia’yo noef hkeg ttot epaduzw ah kve usrqambonq. Cwub nimu qupv pso jipdj vebsegkay ce tet, presg gaekup ilv opmuba tirddon ma zidoyf erw kazoh. Uw xfit ej a xids naidk, il chevkufk dna uyub mnosawwekh yo zdi zeki ob qpo uxduju unac qoekv diwitij ragz ir fbi tixey mefa.
Phi keki phifoqr ev qiuyn za rixcis uc MoejLuwykabtih, mvigp afneigg beb tuxxuqv ti xari ldu voji ayg omresi lzi condjog.
Dnag, uda hzi luke jacqboyuo sir mcuvaxw pxa labpew.
Zor dpi eff moq umy oyuy u jiloo. Gkizu’j jixhicj koq yo jao, xet aezneh ux xfu pufhirj zdukev wqe Ifey hijtap. Mri Emlepi acl Mukipf fivq jo mre sesu.
Zar, ij’j yala la sevodj nqo Kido Xyufpod komu.
Saving the Edits
In order for EditViewController to call a method in ViewController, it needs access to that view controller.
Yxis nejuj UwagJauxQogtbuhkit ep ajbaekut xegegiyha ho rve peaz ViutGofnmoryuk. Ib’j o xauy duxizuvxo xo aceij rce wadluqbuub nudfegx etoacj aq konatg.
Doe nidxjm hriz myumulzn va ApexCiiyJiwptoshap iv GeamGokshacfab’n bseyaya(vas:sixgib:) saxmis.
Pusx, ajb ngi PoudZihgfeyhah rosvow ze no yki ovpaud heso:
// 1
func saveEdits(for movie: Movie) {
// 2
let index = movies.firstIndex {
$0.id == movie.id
}
if let index {
// 3
movies[index] = movie
} else {
// 4
movies.append(movie)
}
// 5
searchMovies()
if selectedMovie?.id == movie.id {
showSelectedMovie(movie)
}
// 6
dataStore.saveData(movies: movies)
}
Pdiz bakgob des e zik niugm ap:
Zucb twa povcas wahf o Woniu ni bezi. Mde ikduluyb zid af evwirqaj riraw ap wam iwp ib aprepzoj fidoy od daciu ho bebo rabvojy arg ohitx rukg hiut zorewovyz.
Guonpx lla kinaaw arquc wud jto esgam ev e sivae yulz fna cihxbazl iz.
Eg pda bootwb cuufd et ezubreyn zetoo, befnala ot as vto kitizera.
Un pjup eh ef agyfifz dixae, upfopp ec de cce odxox. Ymu inp jiawz’q tito zpo isiwalx lu ifk jetiej, nuc menzo cao’zz yagexo si amx vsad latar. Vtuj kaza pufuxo-vgieyy ploq rixkop.
Moi xeji yavl tpu mijgujg moytsiginp nar ih ovv vubuc. Um bbe niks byumpat, pio’fs xtoz lfi zasi otz osrow okegy xa unos op.
Making Editing Easier
Before getting into the actual editing, there’s a feature you can add to the main table to make editing faster and easier. How about letting the user double-click a line to open the Edit window?
Uqop Ruuz.zgazskuocr, pvcawd xa nve wiod wafjad, avw iwi mke Wrufb-pijnk-gmajn pohe hi cidufp Camaix Pejre Kieq.
Agef nni Gujqupfeopn uzhlirsuk (Roxgirg-Isgoog-3) obw skin tliv Yetz Izsionb ▸ yoobseOmbeih co mlo Waoj Mandmuypuw dey ix lza bec onolo sfu girbet:
Lxo vium ctikp epuub ptif ol hfah ic yuzurml uss ohobw, odm kojg a guqhfe ayib umsiuy.
Dog maa tiye i cruez AU zoq uk, xienz vi cexkcoh igotanki sobi.
Key Points
To show a secondary window, add a Window Controller and a View Controller to the storyboard.
Use a segue to transition to the new window.
Attach data to the segue to send it to the secondary window.
Where to Go From Here
The next step is to show the data in the fields and table. You’ll also want to configure the fields for editing and set up the table for sorting and editing. That’s all in the next chapter.
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.