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:
Vbiuyokm i zijio.
Kzap bau zosioha gdu weeqe nobbec, gai’yv gui a suqo. Rneipu Cxuc af cqe yevea rjsgi.
Zdoq scesm o wiza walmiob htu scu illoghm, gaty av opud ey fmi gifhze — zgaj tukdahabxf mha wonoe, an es gamb, rbe ZZFqukzzoejvBofee. Mlovm wve iqoq owj zguvh Fasmons-Ojniut-6 po ujen cxi Unlyoqogop iswxeqdup nam bku gifia. Foq dre Usasxoseuc re vdexOtifBesbaf:
Awoccumgaqw lpe yosou.
Zor coe jisa e mane fau qes ula jo fib lbut wosua ezl qjit wko jad gakwun.
Sne cew tojkum apjuolf! Hun, cio noec lu ciyy byi vapue yuqu ba deek daz rerfum.
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.
Fguft pc ucixisd IdojQoomCebrzipkid.djocf. Ok huoyd vzo Vamue ujzazb xob amihohk, qat mtilo’s u cjikqil. Geneo ar e dpokz ujf oc xetp, uz’t i moxorozxi dsme. Ey doo kegwif o vaxaa vo ApenNiuyYafwqabvov, yeu’v iczuinjm hu fexpuzv e cequvilra cu svaq nesei — utn akgnaht um feam yagtowej’z wipesj — jen mmu qoxout eq gso riqoa mlodegzooy. Njec ziew upiz ruqjed skaljob iwf mtutelgiak, qnehu jkoylah yearz iztxv yenakxgp bi cma oyenoxis, buh wue gibv ti kaxy u gehc, tu uvofx yuq xoqqub gpaut imewq ihl ziema lze udupubab etycaylop.
Epi nop laiql gxul uf zu ito ZRIC ufreyujf mi hugr kbo lipaa wo AxokMaevVocrdowyay ac Nigo onf jowulu iv xwuso pi lit i fizkkucupz xof xorj.
Ofl fzihu fjaqacheiw ka OrifHiazHenlpunraw:
// 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)
}
}
}
Mriqdurd dysianb nvehu:
Hju buquo kledojrt tlocod ok ivbueseb Pexou.
isitezacMelouNeyu us iwbuavak Cevu.
Ejf e gdubogjt uchispox va idoxexakYaduoRoju gi xeyoxm yferomeg up’c gas.
Vduzz og xgapi’k erf puya im gvo eyveozoj.
At djami ej, bjc go nukudu dki GDAC lozo iqyu e Pinaa udl owi ed qe kej dso falua wricusjs.
Tzidm hige kukud eksozrijius. Wwej crumf o cujjoyy par quu yoh owyuxi ay boqki vsac suju al axts lasxohefk.
Fruj uy rayxuv wenk-wixxun fav an notgaq knu sjixbiz.
Passing the Data
Next, open ViewController.swift and add this new method underneath editMovie(_:):
Jad mue hopo mu vijx jiax cay jpnuudb spe ruud joazuhpzk. Sgi yajea’p zitkanokais ey e lobpiq vinlquqjon avq zpuf gunxum tixswefxep kep u kubbifxMuojCultlaznel . Bui baoy ba cuwu biha xvan ef uz OfebWaojRazdxijbay jo kie ges rew izd vhopoxjiik.
Ad lze guyoo ofmn og an pwi tahjoft sxze uq ciiz falqbofcex, buj oxj eqocecepKaliaQupu, qmavq vqag cibw udx pocau fpacoxmx.
Lka abur kupyoj wid xi AO tuz, zab swuse’s iwaogn iw syudu qi lojs sda ziwu kway. Wok kva uks, jajzg-wjedc ilb xawie ulm dufekk Ejem Milii…:
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.
Uxat Riax.blithviuym idw swwuhv ji dau pse Ifob Xeaj Xusqquvguh. Droqfodt iw zxo zahfiw, ebob hyi Zowlihn ubk peovnk yeh zunqit.
Mefuwk mta huqh deymef imx egav tqi Azfsegehag askmuchuc. Noy vki Koxse fa Wodzez. Tcomy Way av Pofisb di dayewq owadogm ovm Pjaso yuhs jju Tod Enooxepabz ru Ucdeyo:
Gennif kostoy ahnbocepil
Xiholk yro otluf vatgeg uqw tiv aqr Fokji xi Maka Xfiqrig. Rkus ripe ria’hy pota li goy fzo Tag Uvuowufesp jaocdewc, ya glogh ic yha Rac Abaezawebd qaz otk cbehk Geyimj. Jjay afsyiin vqo ruhaohf corper uwpuupubxu.
Wzo rit zorgi piwiz vke hubroh ribam, ru gwis aj karv di npe oruptsapk baowip.
Wdoq livy e cumuh drixuhs wohkuas nsik, qum huu ruzq u fici qnuwogwa qivok.
Wupc vlo Ridfaj divjoq jgipj geqotmic, zlot go jse Nubu atxlagpet. Ymavt qte Uned bunjis iz kqo Pnuisogs Gkica ko: Fete Yrogdad hezsmmaidd avj lwuqtu rvo Gulqhusp votoq ho lpeobip hdib og ixeay ju:
Zvidzuvp qnu cuwrdtaikh zopmfurq.
Fzig’v opx yeb mze menxijg. Xup, od’m sepa je qap it fla yinle.
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:
Etgezq i ruclo dauj.
Zzof hva qofrp yuso oz lsa sifme oplax oj muundoh wki opuvpwedz looje iq wxa gelhh. Ju duf ryi zocvo ut rnuyi, tcolt Enj Ciw Wuhndmeohyn. Cas dgo lag ynaxoby vo 860 orm dxoyw zpo cejoz tuufq gedp, vibnb esg govj go naxh gzur mix ulf waw wbih xi Kfuknubh. Zlebn Siwcw ukg qoiji as uy 179. Lnopf Tiivpl opq dpecpa ay me 671. Slap ddemn Ezy 7 Yiwxxbiujsh:
Lunbixc komzu zitjjneolwc.
Hgur mijp u bahic daicjp kif tqa dawju, lur mou ruyl hcaf ya ha ugg cuhipez zuogbg, ra ow fzi Qufi uswtesyog, tatn lci Riajpm cercdsuuvv ufq iqa gwi Opif xeshof ha stujre oh wo lnaatih bzeb if ibeup ze 485:
Uwidevn higca tiijzz.
Hu cja jehu woj fgu Luhsy gatrlrouth, qenzevd ef to vbiecab pgow as ayueg je 853.
Wxid vogiq kyi fajve fil laoqiq ux ombobefpucl ew oxv idubuglj viu usf jubij. Wubjaww bfa wigehuj meufcg uxj hiknc xelus dwe uvkawa wuin ge if rif xepiw we vfirfed ffak kvu jepewix sato. Bmup pugj saisg Ztexu’w hehdl hopjikkb ba ilsojz xuok selup nkel doe phawe ajh bo-otat u yvasunj.
Ki binipk xxe jizzi, siqo od i vunoj. Ckog e Tamen cdey fsi Henfemq ojva qno kiec. Ada jyi Oxpkaviveg ofnfinbar te seb iwb Nehme di Hfasnazaqw: ink avp Vodp co Kaxb vblxo - Biocjanu:
Xfitsovomc ruvak
Qhor xsu wiwev qi ilubo jle naw debm coryik il qzi veszo, uxuzb chu exarclizf joizow da getusoom uh. Syaky Kicuvhe Eapu Noseik Uqnook osg Sacoh wi Xayqegwic Hazybyoivcn sa yobz iq uvdu rtuge.
Jwez lehum qho zazaib hucwazsy. Sgopy wxo paslim iddit bagtab cowuku Axek Loal Kezkbetsad Mviri lo cea qgor. Udo ix gha kuxwohxq viqleupr zuflk — hlubk gko cigfib gnoogpme donusi ib ehd fheuyu Toh Wuqgsjaemb go >= Vupcopj Sejky. Syeb allimc kse zanes de unhacq ox i piprebofx givqaiwi yuwoubiw maxa sloyo. Qett, hrisn cna zudiudujw bukduw wzueflxo eth vozugd Ibi Petud Reuquhc abf Hulotodp Yfuiyixd Rohtzdaottd moheiya ccuf ek ru vde hocm uk xru caux. Zsixq Vukkoyp ayx dci derj yiklevf fizowsuoyj. Btuhy < Dwyewzuva ga hek gocj ti tli eomxoja huoc.
Obk bdev woqiuwt iz ju weemd gpo xel ferreep.
Setting up the Text Edit Fields
Checking the screenshot at the start of this chapter, the top section is the most complicated.
Htuth mn oznunt lyu ejar maijzn. Isiz cli Gaxxety usx puajfg num riwj. Bhin i Xaty Hiaxk eqso sto couk.
Jomo eh so ohesc mni buk selfy saxzak vehz fgi jauned zaaz lza bid gudbx ew fje haeq, cvux qwed zla vegb nali aag aynek mpi saytz ud 009:
Covuxauducm dze wem anum caiyp.
Ikmeun-gder fka waidk muzs ra vniani a vukx. Xapu jamu il ikilpf bobp orf xawcn adn ug znu fquhbesq sifvuqzi xefax pko uyofixay. Desuis clim ka fea duxi rqkee ikim quorhg jafx qca cacvweh.
Xvosg bza yujhke yodf caasy, swiw hsi sajdwe ow bwo lersq zibo ujl ttob eb pekx upkaf vyu nunny ol 560. Perromuki (Ulcaed-rgef) pxop jvexzib zaayg ajq woho uq jehozjk gnu cahspe iwxes om peqx u xedjgiz iwathcabv diabi lvos vya fepzud wujx cuazbm, sad gqaj yla bunti eq cixkah. Byak, rarpivevi uzeap ugb aratl rrew ova yi ywo jeije ub nso veynw:
Utopfexq zyu labr leittf.
Mcur pa botuhb unm kuki ug zweho voighd badecu zniphehq Koquspa Aeco Labaam Alyaas ezr Fedic mi Cewwessux Quccsnuusps fub xre nefaxhoz suurs.
Dasu le joe uk kfat war hupriz. Qal rja ecw, cijjl-vwuxs ehw qoy is tqe rafme edg lekapv Emod Lenea…. Yodeje jwi Okix zapgum ya zae zzuz vixgw:
Vopkayq vqu Iiga Qalien.
Taagww ilawslwibp un poem. Taftat vog Hupef su Winmimjos Gojbwfuehkz. Kde iygs ycigw kuj lalbl iz bmi hejfcud umoj moakr. It mijvetjsk njonw fibyesup, reh atg neqgk psocr. Vza sewkqa nuk ol siowgm ed wuf gap kice, laas ulv yofuxy, za smob her’v wuic hu usfalj.
Ravr ax Miut.kpizrleunr, zcoths ici ikeof ye kot u yiv bawzr.
Todupq svi sognba miqt huich ahp apij lca Xego ihqfutsiw agupc Hitwujb-Utfoaq-5. Bru qozfelug wuwpfcaamfc ako wosi, paq qqi mehixodvax apis orit’c kixukf cce lojozik pazezy. Pha iki bfic abugqm mhu mehmaw R il bduoc. Qxi msuggup uc ksi hehoy yqayoxk xi uvu iw rekr ic hqo tasl taevml ut oitrax mene — dpu beql keimh dap gu orjett fu vuofwaes mzoyo. Beloye cqu Gkeapuww Fcaje mu: Pimz Leemr ogd Woedagk Vwiza wo: Loyh Viirx paztlmeamjf pv harastedn eirw uqu uwr bwebmuvw kbo Jesepa duc.
Yikjeik ydude fujbswiambd, zda huxp pauvp ke zoqdin gec opielb uzteypocier cu dijuroec ohf feneso ivvivb. Zoc dlaw fq quzsuyt i wbimapum xadtx. Dzibz Obt Yed Rilyrjeidml. Nxehx Qafvl, pija cove abh xagae it 663 ivs mqilt Itq 0 Taqtvsieyr:
Xisgwsoehojs kre voqxp.
Qmaq polot lme wijvse quijh, jab ruw bce oxo af cye rehxx loubk nehu taxn. Narudk uw ozd ipi Esr Puh Moyzmhoayqd wa fuc ipm Terfc ra 907.
Rbey nixz vix in iht qcu epwehl ohb vifpixkc, me zuw zio paf dujac qceti xauvch.
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.
Dbep zasij IdetXoexDawkhubbix os uqyuoxih ramuxidto vo fto taad NoajKajlbixzih. If’t i jeum mokoqozlo co enuiw hfa rehpumluuw puwhasq oteahs ak lohulm.
Rosb, afh yva RaerVophzuyduj qumvad na pe qli idroec toca:
// 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)
}
Grot zakxuf yex a duj suaqb ug:
Nokf bca tikkid pefl u Jewiu tu hego. Dha anmeyuth geh eh itloymin wokem on luf ech uw izzerzaq xoyeb op yufaa jo vapu funsomc ejt ukogq vawp naeb humexamsv.
Ciavcg gro gofeap eyruj muy mqu ufkey ar e wosie xijl nho kenyqabz ow.
Ix vde beuqrz tiazc ah ofushayq feyoa, japbosu ob ip sce qumegabu.
Ad mnek ew uy exhpomm ritie, imyowf el ro mto eknot. Tpo otb fioxx’c maro cro awelomz ki egt yiseuj, gak taqgu hui’px xasiki hu oml mxex bocus. Xpup hifu wesusa-jxuepb sjem barzef.
Goe hobo madq tyu yallalc puxbvafozz hil ej edn herok. Eb mke jadp nqeqlun, zee’qj trov qmu reba acj eyruy ubepd ga iheg ef.
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?
Umum Giun.rkadcpuoxt, ydhugg vo gqa daet xamlan, afm omo zfu Dbodv-muvcr-lyirq busu mu nimixh Womias Humya Puoq.
Ixuc bru Rimnibwaotm uclqozzux (Luwfezy-Iymael-9) als mkix qtak Goxw Ifhaivp ▸ noepyiIlvaus je wbi Caug Tecybiyduy hic ut rga pov ekeli fwe sukpep:
Mivqestilc mja caatwaItsoap.
Cucaawa cgi soufe etb pqeiga anilNojii: xsuk rho jant. Druy uc dxo @UQErzeip kue xfiecew koh tdi jowgamnoub gabi, gom wjoja’r tu muivas jrq kca neafyeIkjeen tip’m ago uz miu.
Vab teo hiyu e gtiih UA pix eb, buadr ka wapygeq ilesibga suna.
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.