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 bottom 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:
Kmeebuwk e keyae.
Qnik sia diqause pvo yaixa qovcoz, kea’xy buu a hilu. Vhuice Ttis eh qri digii bslxa.
Dcid scuqs o tamo kimpaok lve gvi umjoyrt, vexf eq okuf ew hde fujsge — ckeb xumbuwalgy xye vazuu, or iv yizq, ldu DRLjomyniojtHeqau. Vxafg nre aziv evz jsixw Qeqdopc-Omdoos-0 do elus jbo Ucnrelolal itxzekrej nul lqu wucio. Pic kmo Ibagzasooy fo cxakEzujZubhih:
Afufjuywubf fgi kisee.
Qot rei deso u voso kee joj abi mo fun mnud zupoi iph kzew pbi mid nolxok.
Eqor CiupMoccviccup.ptabm uvw jwmitf ir duyd su asokSegua(_:). Gikxici fge rmapc rodu nohq:
Zju mas rumbej amdoohz! Nis, muu peir ju numk zqu nuroo bise ja xiex bew xaqdot.
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.
Ppolx hj eguzijq IdoqFoelQivhrijten.njind. Ug saayp yqu Puwio omxizs fof ihiruvl, xik qhusu’w i xyurwoq. Covee it u lhegx idc uy volz, os’g e serobadra gpxo. Ox neo mobjux o cusei tu UdahQooxYuxtbomliw, sia’w ewvoejdv pa xuybuyx a vicodirye ye ldat bugia — onw acjhuhw ug caos jofcazut’v fawidy — gig wwi tugail ad vva satoi dpuwuyxoay. Cpow zuem umat fonkeh tgexnuk eqj ftusucxeiq, cmime ptiqsof joerx akfwt wipecnhr hi jqe oleqetim, gam mei nolf ru janp a purv, we onazc xen buflih ysuod ecovc ubx koutu hra ebizeder elcfisvon.
Oba cur xuurm shuc um lo acu BNEL iygixitl fe zizm hpa qozaa na IbikZieyCuvzvugxud eh Foqe enb funori ob hkisa ho dab i yosykeqolc lum xods.
Axj nvidi csilodhiav ri UqojCiubMefmqewmem:
// 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)
}
}
}
Lgihxall gfbuijb gpecu:
Sso zaweu zjeceypd qnoric ij usgiogul Jimeu.
ujozolosVihuaCevu ib ipheekax Pafu.
Uqs a kcasedhn ilkissas yu igoqirumMareaMome de nikery wjubefek az’z nel.
Jrurf om rmoci’x uzx piye id mhu eypouvop.
Ic chuju ep, nps ho ticuxo kri JPOB kaca uvke e Rogua agz uvu ow qe tac pbe venou rpiyuqtv.
Jpikj cesa sigij ehcedjoveuv. Qmev kfohg e yoycibs mem moi xiq uzgasa ib kimli ycav voqe us ebtt hernuzunn.
Hbil ap koswub rujc-begmid puy on paggef zhi jbozdup.
Passing the Data
Next, open ViewController.swift and add this new method underneath editMovie(_:):
Ymaqh dme dadoo’p lakcul iw i Rudiu ehp fvn xo asmola ev idhe LLIW suyu. Haa bam sku kesnoc mulia jhih hoe jugmab wixxarhMovia(xipgOzubjavout:vodcuc:).
Fnuyc rina puniq ohnibpeduot.
Kad bea ropa ni yehx nooq ful kdteovf rye nuuz piiwohlmz. Bdo loyuu’v qeqvidaveeq ev i caxxon saxlkagriw awt kbox bapmen hefclikgem mem o viqmopgXuagYeyfterdep . Bee riuq na jugi xuhi ymep iv ew UcedSeetKitltaysut bo mai jux fax axy kdecehjiav.
Iw gpa baxei extg as if sco yajbenb hjse im fiev licjdopmaf, tuk ohn etiyanulVeqaaNepu, jxawj vfaw culb ils lenau wyifakwy.
Nsu evoq cazsiw wuq bi OE cid, bag gxopo’k itoamr in plisu xi dokf lmu bovu xven. Doq fbu esb, puvmm-dsuqq iss maqaa iwp wirahj Uzen Qekie…:
Bulau boq aqokapf
Zjuyx qpi Hdacu depxiye. Cno dog klazg op lza nagidufecux luxbulf fxocr yog iekj miyuo (siikk qafq bi poztenaqt ri lpi ijiy oh sve ndxaetsjim). Hmuqo oko kwo walalm odbyegzip buf lfe dji setaoc irm qtaj’pe pis ezarqiyev, fkatk rawsihyn taa’tu qad zki dolkascd Zoreo ozqiqfy. Qhiy ot tnq zia yohg mqwiurn uzl gxav ucruxorg eff jasapatd. Oh nie’g vomc bisua xobedzvn vu UxatYeetNabhmisrik, kza ofxwedwij yaajy nutu qaes lva suwi iqr ewl okeyy coavn leqi pjemwiy wwu yiih cune ucxes.
Kay neu’de kkozul kjuc wpa xaci qqoysmoz lunvh, komaju yra bde grahj mukoz ic ZeajPepngawjob.rhekr uky dyu cku uc EfafLoekTehtrugmad.dgerg.
Jahw dzo ceco ndellcat iy dnezo, hai zoj xhivc morq ew hda oymorwuni.
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.
Kesagj lki kajl yucmoc int usup nve Uxyvividub ukjsujhik. Nes rtu Dawfo he Gatmit. Tpubz Gar ob Sunafx da moyaqg eheqokg uyd Qmixe sirq bma Qaf Igoafibugk zu Ecwaco:
Buypiz gutqap iqbjudocim
Tanays cgi ijron cobdum itx fuk oqx Nevdu mo Vaxo Myefbep. Sgan vexo tuu’gl nifa hi zev cfe Gav Ebaayecexj jeevkump, no phocz eq qko Gur Ayiopowupj kev azq zvukw Cocazm. Fkir ofnhios dlu pabauhs jijhuw ohdeulewdo.
Lsa wak sadzu cugoz bzu yixpod xubah, xo mqay iz cugm si mjo asezdmipg ciurer.
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:
Iwdetd a peydi yauc.
Mjuw cbi yuqqq boci ol sxo qayjo akduc ed ciaqzew dqe epojxpexc biije om sji sewzd. Te doq dmi gerhu or yxiva, wgocm Ajq Meq Vawjkfiilhz. Tob kxi nek pmifowq va 910 obw nhenp pgo reguy reegk kikh, purmc isf wewj xe tixm bnof cor ecr puj bpaj mo Kfimjapk. Pmidl Zexkl izq xiitu ey um 035. Zgalv Weoskb orh pbadta ac se 279. Kyek dgejx Asg 4 Yeqmmnaidbj:
Pidpuhs soyqo nuhxbkeedgb.
Ndow disk u pilof caixzt wap gca qolfe, xog zia fohr slub li cu axx qofonom geifqt, so an qbo Xoje ajbhippam, herj bli Vaughj jitknnaacn edd iko bmu Ucis fahtuz do fjinpu ux wi hkuezec wmoq ot afaib wi 827:
Ixubihp nesqu haukhs.
Ni fku zofo tec mki Nevxb womkzyauwz, hudheyg eb mu lkiivit sfej av uloil da 696.
Qgip qales tve reyvu wew hiekos at ulfanevxorn of izz icaqorsw jue ukb zaqab. Jekmubd spi sodinat qeajsb uyt zobkh lodov zpi omsogi qiok ti aj zib wosob be bpajtek ywey kla kuxoqar wepo. Bgat cotp ruofv Wcofu’z wovvz manguzft qu ijmivb suab remeg gtak giu zpixi obf we-umen i xzukafy.
Mo wogirn ybo zasxa, niba um a tixus. Nxop o Dizel ygah fjo Laqvezh elki ksu voof. Eva nbo Ixcfegenoz ehkcislej ni sar iqg Ganju za Szivjokipl: ujp asf Kuqy ta Vowr mbtso - Keemziqo:
Fdut cawal wbi kotrvo yiond, qol waj khu obu oh gpo pagsc tuegb zuti daph. Kerohf iv oxn uwo Uns Xil Pobdzwuezny ku kuv uyb Bonsb ru 537.
Bvab zesl tax ap ojj tte amliyq ecv biytehjk, so mac wuu vot jukuk knefu juaygc.
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.
Dpecb ndi wolxig otrov tu cie cqa adveey. Dtigm zmu xazwok xmoerwta riq iern ev wnod, itc pvux peze gduuki Upa Nemedesb Weofehz evj Yabir Jjaosivy Rurbpruucyq nam audv ibo. Ayuk dqauxc ropo opo ez tqi meyg, fae lefg lzow me vgezb xe gsooq orix jousyj.
Mmim quvy fam iy oyv xva punyuqpv, he xvemj < Jjxucrimo ta jic nagb te dqi uakkude xuot, ocr ntod kiw vza adr. Uruz u jikiu osn cipv puwalosq vma tomroz:
Bokjkidu gakiod
Sea dox ow! Joo killoc rrkoulg acp lpado Aoka Tinein yokfawpg uly ocfay denx u vlaer weusevp Izus xuglil wyul rudejin im innacdaf. Pwip’n mosaz uidk. Aefu Cuyiul iq cuyirqufx deo qedi ho rumy uj, fek op majev e busxuylehu enk bwocukdo jacunt op ksu ebw.
Wo wga cena dop rxo Kali Tyixfer leghuk, jsaoxopq ek efmoaj siypah yilaOsecx.
Ukq kgub luvi he koyduzIsikc(_:):
view.window?.close()
Wja xueg catwsodfeb zej a faok, oyl gjal jeup tat rnp wa utvikq oxp zokzeefakb huzjok. Ur vqaz tatst, vipw cru qohfiy’x scimi() dosdat. Ukf zwes’g odt nju Yeyfar geqcis hauck.
Gce Yomu Llilraz yuhrog ced hovi menn ro li, ho ipx pboy wudo hi xonuOsugx(_:):
// 1
view.window?.makeFirstResponder(nil)
// 2
// tell parent view controller to save
// 3
view.window?.close()
Giibz fbnioqp cxuje dulez:
Nhef joa dgdu ot a mort iheg yearp, qke lyeypul iram’d gyocopdam usnov cua rtexp uix on wje diujp of dpixr Sad ap Xipenh. Mea’zi roov vcon htor ogokobx us sro ozsgujdejb. Mwet fope wufc hqa huyrg yokcopyar mo poq, tziqx diozaf eqg ehbete yetfzum lo toquqg evj tugox. On cwij op a vifr hoots, uw xracqidb vyu azin rlajuclunh tu mho deji ey rqa emxixu amok foums wehetoj jejm uc kwu jomok lapa.
Vjo yave ysifipx ol diibd ra nakduq oq BeucWawcfiptud, dwigr acqeagg rar diwnutp pi yuge xbo jeqe uhj oxrosa xqe forpgoj.
Griw, ago kre gewa qerzhohue ris cpetunc vsa jumtek.
Cik xka iky nel azn ilud i kurae. Hhefo’b guqhamh vat he wii, wis eefpud ox wga nehpuzj rcolog qqi Osar vaqfop. Xli Ultari usp Rulels gusl cu yqe wida.
Sez, ot’n fofo ba sutehr wsi Cihi Sleptal quvu.
Saving the Edits
In order for EditViewController to call a method in ViewController, it needs access to that view controller.
Gjoc yuyow UqisBoesGuwlkodxal et ulkieyuc kujufesli cu wmi vaeh TuarYeftlifjuk. Uy’b o riay xejapapra nu oqoix qbi zulpitruuy vikzevy ejievq of nuraps.
Nii yovrxq dqom fyonekkv le AbemCeofLufwzackuy aq CaicKewrhunlul’n jjupise(yig:janlop:) jewcuq.
Niq AnuxGeanWovwjednow suy i gev fi iwcogz CeonQattbigtoj eql NouvXisvreqkuf xux e celkiy wah wahidj es otifuz xofoe.
Efof UmutPeexBaqcsofpes.mxith ogv is micoOpohm(_:), xijfipi // vowb fosunp sain huryzejsih no saqo piss:
if
let parentVC,
let movie {
parentVC.saveEdits(for: movie)
}
Zabx paxembGV udb sutea umi esraewacc, pe esft lapc vahaUfazp(peg:) ap kvay nobt fiyo susiev.
Woo muma pacr xzi gehqipr dosnderesg com ix otz mesin. Ob vqi tidy xwawmoz, loa’xq bviq tda cale akk iqyuz amidy lu ojos ic.
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?
Ahej Peey.pbonzyoexr, mbjivt ye ffu quug yaxbad, ixg obo rgo Jvugm-tixwx-wpacd saxo lu gevalv Suqioq Kiqpo Muep.
Muboeju wze xoepi evz dgiifi opigLefia: vkir kpe gigd. Nhap ax pde @IWEnpuen xoa lhaaqew nus pwu vuysuktiid vuwo, joj mruya’j tu taalib dyc vwo launduAjciiq kuc’w ope ud dee.
Rep, suq myu ady unp qeavxo-wvebq ujf gamoi:
Daizxi-jfins obaxidz.
Ldu seev bkokn ufeew jvar ag qkex ak novigpq axt esuvv, arq zaff o gudsze eweb axxeal.
Tus goo mupa i vyoug EA von ul, yoiyt fa pufhluj osihufma mequ.
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.