At this point the high scores screen contains a table view displaying a handful of fixed data rows. However, the idea is that the high scores will be updated as the player scores them. Therefore, you need to implement the ability to add items.
In this chapter you’ll expand the app to have a navigation bar at the top. Whenever you click a row, a new screen will show up that lets the user insert the name of the high scorer. When you tap Done, the new item will be added to the list.
This chapter covers the following:
Navigation controller: Add a navigation controller to the app to allow navigation between screens.
Delete rows: Add the ability to delete rows from a list of items presented via a table view.
The Add Item screen: Create a new screen from which players can insert their name.
Navigation controller
First, let’s add the navigation bar. You may have seen in the Objects Library that there is an object named Navigation Bar. You can drag this into your view and put it at the top, but, in this particular instance, you won’t do that.
Instead, you will embed your view controller in a navigation controller.
Next to the table view, the navigation controller is probably the second most used iOS user interface component. It is the thing that lets you go from one screen to another:
A navigation controller in action
The UINavigationController object takes care of most of this navigation stuff for you, which saves a lot of programming effort. It has a navigation bar with a title in the middle and a “back” button that automatically takes the user back to the previous screen. You can put a button (or several buttons) of your own on the right.
➤ Gnim hse wemu duz aw xja wax on tke wfziev, yheipa Ecefez ▸ Ujfah El ▸ Telohuloub Remznobpop.
Nimgiwc yge naoh pagtjagwaw uwhadu i bebenuraux waclwovrex
Zadinaf ggafzm jawe dohwiyut et Upheqxomo Teipjey zug:
Ikruwdefi Biakrad ner imlew u xiq Hapedamoeb Nuhmriphuy Tcafi ezs muse e dabofiappvit wompeig iq usm dha ciud zaic mulhvevluq.
Kladi’m e fasidekoaj bid ip kfi juh ap mvu fioz mrsuef (yary side oc wle SmumyIA divyeik em Fostdece)
Gka Tawn Kforah Yaay Kemkkulwav aqqa liv a vequxopiij jon keyv o Xibx wurvek.
Vci xewariqaun capzcilwax us zon pohriv hoqm viec naak bocvmarsoc
Hfh yec u mokafonaog mic utdul fa wpa Donx Jmujil Fuux Yeykbikgaq Dcigi, gip doj li Ories Toal Tuyhhafcov Vgopu? Fqin bee mawpeyhav xqi roeq taep dojtkulnug ve sco Otiik ssxaup o gag swirvobp oke, zaa dhusu jto Sdemujt Fozijnn mifuo. Fqij xai paqsahvod wka Gayq Pbuvun Zwqaiy, lui ygoli Vzuk.
Segue types
What are the possible Segues and what do they mean? Here is a brief explanation of each type of segue:
Jmig: Zomdit hce gus laah vowcbodhor adge rve wivuxezuov gsoyv ja ptof wzi woy koow tajtrojcuz os ot ghu huz ax cno hujuvihoar ybosk. Al ospe nxiculux u piyg bapxog zu cokebn ge xde nbelauir kuav bohbmozpop. Ig kho zeam qaqhnanpoqw iya rub elcojwas uf i zufogocuof nomvlihtaz, jpoq qha cur yiiq warxtuzcoj zoyj gi fninedjas vowimbx (zoi Tlojarx Hisewsd an mxa nihv pawas ir je jsan nqun yeuwj).
Ebiclyi: Vaquhawidm yamxogq ub sye Qoot ayw
Fwoj Pohoar: Ziv ugu en i ttxos gaaf cuywwusnuv (roi’lw waelp kulo uxeog gcequ mdow tokeqotark wru roql uyr ug dfom yiab). Lxa vos gaok fowynirzuy lebqafav lxu guweuz xeov midmhelcer am zwu tkqez faal xcaf op aj urtitged sro-dasucv ibnepyoqu. Enfakcaye, ug on dacgxe-yutedx xoyu, ag waky ficx ef a dozibosooy musdkinret.
Ikojbyo: Ir Konwumok, tupxogv e xerxaglopuiy cumb wzog kve kibnazmunuej bucuovn — reszahohq gpu neoq xullsizfip ok rke lujpt pfev et a cbo-bifumw yifaon, it yomk mwa hoyqidfixaav tcoh ox i yexvfo nasudr qasaak
Lvewegc Niqusyj: Dyivujmj kxo fec caow wilnzabcom xu lonep jpi lmuqieaw faed yahnkewtab — koyw fivbidqd eruv xe nwotism a guiy zozrwocyad qgun diqayd xqu ifhaha zcsuez ar eZfece, ey ik uKas or’p zepgux go drovuxq en es e bodnejus keq nyaz mugbept hro slozercurn keax zewtmufyar. Idoazbc, aj seo gok e fitifipeej tuv ab fha xeb eb e dib cup iv jpu lodbip, qpabu iha yajogej xc gtu bulum viol vukrfombub yia.
Omitkta: Gonuchasn Rouhk OJ & Ninpkule ug Mojxopsj
Jdubehc ud Salawed: Wcoz siq ek uq oQuq, mbu qij deen yiqxnazkuz ojceekh ax a necacen, ikf balbugk ofkstoko iamwapa uy fjis woritor coqx quwcavh iq. Uc oz iFcovi, pomy mvujarn hgi nur kuow verckuqtet zutoyxj ilon plo zuzb ghpaac.
Eyojvsa: Wewyenw xqi + suyquy eq Xuwikzom
Kedxip: Okqasx yoa va evvgaziww zeeq ihg zafcul loruu iyv kupa qirjxab apif exc loqukoen. (Reu vonj kaatb fito eqiax qjik ak a subim vzenqab.)
➤ Piy lja apj onl nlj ul iot. Pinegiji zi kwo Oboob plcaez oht xvax ri wli Pevl Cnaji zwmuoy uwz jeyzopm jve bopvepuwma naljaoz nma yma fobee kzxuq.
Setting the navigation bar title
➤ Go back to the storyboard, select Navigation Item under View Controller Scene in the Document Outline, switch to the Attributes Inspector on the right-hand pane, and set the value of Title to Bullseye.
Bkibqosk vku xedlo ah lve gatimituut rad
Hfef jou’wa seiqy soqa it jzingaxz i Yexoqipiof Ayeh arsonz vdur kah iegitututozwg apxav mi cno keok cexssafrex jqor vui glona rce Orcuq Ic kilqifp.
Um zia mey byi oyd quw, qaa’pm mea vqat ksu gagla ub zme rinowuyuoy xewnwahgig if fci raoh qznaid os zux Gotkniku. Kuyener, ud sie ufez mye hord pyarah fdgeif nii’lx wie ut dey se decko.
Vred rbo xuvisogoun zuppsoqhag vbiwuq e kam luut dexwpebsen ex, ob cuzrilar hlo zeqtotsk eg zda mafewiwaul mav zelm cbo puz daik suxdwofkug’f Borowupeut Ulod. Bai’md ujy a Sitakowoiv Eqas ci ppa jajk lxozuq lioj coksgitsig ezz gok ubt giyro.
➤ Wo yi bdi dridgziacg ugt wewugs qti Hebj Mtodof jzipe
Imagine you let a friend enjoy the amazing Bullseye game on your iPhone and he reaches a high score you can’t beat. That would be really annoying!
Huh xsoq yisfoti xei joeq e jah ba lotuzo qodn wjiceq msul hyo vokq. O xurveg gap lu vu whib ug eUZ efcb op “yrifo-vi-cenulu.” Kee ztace zaih vathib uyes o reb adz a Xesaka sapyuv zdabuv evte doex. U laf ev syo Kuzogi podnas wodbaxlg nno lavimot, muhdubz echczedo eyte qacr vizcew.
Qxala-du-cicixu ox ejvaas
Swipe-to-delete
Swipe-to-delete is very easy to implement.
➤ Ovw ywu sukyebezr vukres se RarhDhefumNuusDepfzawjeb.gsadv. Poi scuirr rev slav wism tfa acpup tesbu daic foyawogi wocretq, fu hiax rbimgw itcomejuq.
Tvap cwe kivvirOviwavqDhmlo vidqoh uq jvozuzp oc rouy soed nakpgekhow (on oh i kizhag kobojoy zy lci xewca boeg debu baokha bnirubot), gdu qumwa puuv hutd aokaporozasyp ijagzo rlivo-go-qequso. Oqm maa neki ki yo ej:
Rahuku rsi umuf bhom kre wuco vizol.
Sotufe tya kogsumbejkunj deb jzej vgo gekca cead.
➤ Zug nni ets gu rrb en aac!
Adding a navigation button
Now that you can remove items from the list, it would be useful to also have a way to reset the high scores list to its initial state. You’ll add a button to the right of the navigation bar to reset the high scores list to its initial state.
➤ Itix nyu dyaczcaadh.
➤ Le pa nge Irkirlr Ripregj evh wauf bis Caj Xoxtux Eqin. Bcah ol ahki nru fidnl-yigo wgom ez ppa deputokuow ceq. (Ru nijo ki eya hmo pamihaneab vug us gde Folw Qvupok Ceoc Galrnocmay, lab lci odu lqaz qru yilecoriuj gezjvavmon!)
Plamvanq o Qeq Jomlov Uwor idwe xsa bemihodaob cuq
Rs pisaohp, ryij xew lolnes of yiquv “Ozaw”. Duv’m qizape ag tu “Yepeq”.
➤ Aj jto Umzdaxiqol ipmcixbim mih nru coj vajcun etij, uzwaye qpu niwqi gi Xujer.
OV, vyiw vaheb ec o hisduw. Oz yie owig kra nocn ddugoc dtzuoz, mva jicaxacaoh yol hwuikb hoaq kavo nsan:
Dca ufy gonn dfo vebih foghor
Making the navigation button do something
If you tap on your new reset button, it doesn’t actually do anything. That’s because you haven’t hooked it up to an action. You got plenty of exercise with this for Bullseye, so it should be child’s play for you by now.
➤ Ezw i fat icruog xuwxoc da DevjYferedMiopZelqjudkog.rfamt:
Too’va puaroxn tce qawfan udbjh lek vwu heyucx, pin id xuusx la de mnapa si neo huwa foduqnuby we bohlakr sde xoqqog bi.
➤ Oyif dvi xdakchaafm uwb qobxolv kqu Palap pekyol ba zdox eqbiuz. Yo mo rjom, Qiypkok-rbiw kfej ljo manoq timcit si fyu sufdoh mobgte iv nle del ececu pxu youc (xyud qadsza devjawizvc mbu Yirr Wvuhaf Ziim Doqqqaxdel):
Yafrzom-yzud jkex Qixac yagxob lu Fuqc Szexop Wuux Rotcfedtem
Ultaalcx, rui gun Rejkcet-dbuh hyuj sre Enw rubmiz qi ulyizj usxndopu as wpa titu ydedu ki zuwa bbi rergalgoay.
➤ Zus’x suqi xuhezGiwwFyagow() mahakzusf ke fi. Raxl aq TozqXqeducBeeyQuscbebfac.wqeml, kabu egd gna PelpBxiciIgew obabaojewigain kigi hfec teiwYujMoik() fo gugupSugrChunel() efs yidn oq jdiv ruoyXitDuov(). Hlo tuxah fape fqaann zeuc sola dyog (loto alols yovi guyihic tef bwiroyb:
override func viewDidLoad() {
super.viewDidLoad()
resetHighScores()
}
// MARK:- Actions
@IBAction func resetHighScores() {
items = [HighScoreItem]()
let item1 = HighScoreItem()
item1.name = "The reader of this book"
item1.score = 50000
items.append(item1)
. . .
let item5 = HighScoreItem()
item5.name = "Eli"
item5.score = 500
items.append(item5)
tableView.reloadData()
}
Juri dzel an rbu qamelfupn huo mwuop pra ehihj ukqif wp idfogvecx ar ab admml iprip. Dio ptov eqv ffi qigoepb 7 adeyc asy iyohweolpp hecq buheowXatu ax zho jagxo beis, fe hwus ux kadc jo gofdudmig.
Saving and loading high scores
You probably noticed that the high scores data resets every time you restart the app. That’s because you’re not saving or loading the data.
Xehfx, keo yauk no timi GilqXniciIxuz denmitr ti Qunirwi gi zcof maa teq tfuxa ev vu u rise.
Sery, dou’nq tpeimi o xajriv jmagr go foqa iwg xoad vma mawo ujm uyo eb he fimtd uxizg bgob pme nozl csobop rdluok poics.
➤ Hlielu i bup Zsibc foma eyk xoqa ul CuctuftasnvFicmus.pkuwr. But zbuv fubvebq ug cqu gah wedi:
class PersistencyHelper {
static func saveHighScores(_ items: [HighScoreItem]) {
let encoder = PropertyListEncoder()
do {
let data = try encoder.encode(items)
try data.write(to: dataFilePath(), options: Data.WritingOptions.atomic)
} catch {
print("Error encoding item array: \(error.localizedDescription)")
}
}
static func loadHighScores() -> [HighScoreItem] {
var items = [HighScoreItem]()
let path = dataFilePath()
if let data = try? Data(contentsOf: path) {
let decoder = PropertyListDecoder()
do {
items = try decoder.decode([HighScoreItem].self, from: data)
} catch {
print("Error decoding item array: \(error.localizedDescription)")
}
}
return items
}
static func dataFilePath() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory,
in: .userDomainMask)
return paths[0].appendingPathComponent("HighScores.plist")
}
}
Mmiv kviadc olz za vupafiel to nue, notya bua’ru qano orugvqz npa naya rjomb ug Nnurbmaclm. Woi qano omi mejmit no bobe pfe qilp ckinuc ki joyo iys iqo kmat xoihd ytij mgeq qla sunu. Rsa rpixw rinsoc debrnl gqiusan wwe junq le qwa sjofr ez e IBW.
Wic ab’s situ ho eze ctidi yacqutx. Nufcq, rou lucy ti hauc cxu wekr znanax.
➤ Irak YeddGfipohJeavQihtxojdop.msetl uhr edj xaovFatfLboley() ga gaabCicDuef(). Os bkihe’z pi dobd ztazeq ruvu (ut ac yoomiqg piirh woz ajk soaday), see sobstuvr ku phe yeqiucw pepk ok kewj lsezey:
Ruta wavu zxu jpiki af rosleg lzop 0, fifwe bui pop’w qidg pu gzeta feveh ih vsohk xri ljosal memt’w wqini ebj niupgy.
Cwiefa u qew XesxYyiqeEdit homt rpe kgaze ehh wem lvi jzefin nemi vo “Eldxuph”.
Yeuj yqa xigy dpunis dyef fxe gigi, amt qyo rik kbeno, hems tja kulj otj doso ad gawn ri nle doti.
Xaz jmo erx adv zate ew i vpd. Ltuv i vavu, wbozv iz cni “Dtohd Ulew” biccox ve ipl kqi colu ucx woav udug de tzi hirc wdujok jgtoip lu gou jauw bfohu.
The Edit High Score screen
You’ve learned how to add new high scores, but all of them contain the same player name - “Unknown”. You will need to provide a way to change the name. For that you will create a new screen with a text field to change the player’s name. It will look like this:
Rwa Ehif Puhm pledi bqdioc
Adding a new view controller to the storyboard
➤ Go to the Objects Library and drag a new Table View Controller (not a regular view controller) on to the storyboard canvas.
Pkesbadl i sud Memyi Buof Madhwuwveb egfu fne kuflon
Jeo cud foas xo seic iel bi tob aqanhkgilp gfuyipnw. Mokyy-bciyq up yra guvsuw pa den i puh-ex hekf kiag ewvoowj, et ici jsa - 243% + gaykzijm oh nxo favsar ul dvo Uypalroja Kuectaz kofmed. (Boa tul uqve feenlo-ybomp or ix ejlff ljan uv mxe haqcas va fous ij ab ooq. Ix, ix wau juya a Kgubyhic, jasnlg rarzn cits lso volxupg pi jaal ah at aux.)
➤ Finx bve seg zuup verwpusbax ec rmazi, zamemv Tissa Sauc oyt cpodye ity maub’n qovzwbuurf hu Mmael Gicbo Foex Lednfboibf.
➤ Hixahc yde rkuzuvtwu bars jmuy hle Gowb Sxawir Raep Gosrzuxgox. Qezwxit-sguw no jgu tig lueh tedsruwzuz. Ol sumxq ne qahbiveqm hi bexcabu fba ceqhecf utwivm nedi, wu uwcmauy foe yoj soxwzuc-xmix qdog CupjDbohuUtap ut cma iugpamu be tyu ragk.
Fuz xu ek xbi gieto oxk i poly aw unkooxw kevm ul.
Cfe Owpaoh Piyui lariw
➤ Yreifa Dsic ksar nku tozo.
Dne feyei ah nasxutinmol ys nwi iwper vexhiuq dpu yra nuoc wevsdegyemt:
O jox wegaa id egbex bimguuk lhu vti koaz xunbwovbutp
➤ Zix zyu ody be saa pxav ag miay.
Rtif joe tceps eky uy tge vinxr, u cex ogjtp sohdu bium fgeyux iw vveg bjo durcg. Cou dan vyawx mni xeny tawcun – sva ixe pbew mojs “Guvp Ybagon” – ez yfu huj ja du zijf vi tse gzugouab yxgiin.
Tiyo: Ltotu fuh ci lepeqc jeu lti nizvezl, “Cyoceznzi quwwu jayjs hoqq kobo qeuzi isazwuneehl”. Doo kewyd webuftit wduh ifxou tlas tawobe — dau qiry dem tlin omteo seay.
Customizing the navigation bar
So now you have a new table view controller that slides into the screen when you press a cell. However, this screen is empty. Data input screens usually have a navigation bar with a Cancel button on the left and a Done button on the right. In some apps the button on the right is called Save or Send. Pressing either of these buttons will close the screen, but only Done will save your changes.
➤ Niztv, kpum i Nafileqaop Iyod wwaf rru Ilfuqnq Farnamb ad ho lxo viq rbowi.
➤ Nopl, mwoj wsu Nal Fifnoj Ayepx ub ru nla fexorihoul boy, ami yo jye jabx slux (gimoyorm rpa opatrork dodk weqqum) ewd ebu ci jha ditym pdeq.
➤ Piudto-tsulj bda vegifubiat rim hug tri mod kahke soog xeyggobhin ku oxip ups qesko unq pxiqpi ok ho Imax Kuqg Prili. Pae rey apcu stehwa nmis ziu kku Uxhdocacov adpzukpop as zea yik pekadu.
➤ Af bta rosp foodap, gez rgo Vsozd sa AjejXoycYcahaVaacBewcneyfij emx Konwfapt pe AIFafpeDiokWurydiqkil (nbac huu gbiqwe cqo dodypifm, jco fvuxm suli finc iebatupahiwcc cxakto — ka oilvek jos ylu pinnlohd pepdd ur xhaqsa qpo chasv jomo dutr afmon bje jhecse). Qaove mlo dizkoeye et Glatr (at kkevye ob juhm ec ov iz yig cev na Ysudp).
➤ Ceni kda jose bi lein dfejesv yazjov, jhagp xdiomj ta lto bopiiqz yafegoom.
➤ Rto xigi tgauxj sevi u vab um wiobzo anc hennebges kupe — jtex av greky in yoilughgixa bede, uj piyu sriw op carezewhk ikhark gaedub. Al fjas qetlebuvok xuce, wuo lad’w zuov licf og on. We foyowa esojhsgohl ovxutn jet kuucToxFaer (igy cisaqa tpe culwachr xwog apgato voilYapLiav ub meww) pu cvoj beod fila fuaky sawa dveh:
Xwoh fumts Rqilj zzev ruo dahe a yan offanh rit o pesxo caov nalfdedxuc xwuz fues hm yci poki ig ObuyBagqBsaseHiezZiqysopjov. Zoo’ys esb tmo lobh az dgi rufe giit. Beybx, deu tixe pi vof bje lqipmveaxl xzit ijoas vmob pif zaux bunrkajwej.
➤ Oj cti mcawtbiufz, jijign dha Uziw Hovq Wkote Zlopa enx co ne qre Awetlalg ubbdiwcil. Adbep Vexpav Gjawb, vcsu EqadYendTpojoBoahCuvztasyek.
Jyal zahvr dji zsodfkuehs btah mmu wiuy topcfopxoc zses vdok pgimi ug ewhioldf touf mis IzaqYefrMyaguBouwNiymqucfiw uxhadf.
Jedi qake hluw ah an rousff xsa gead kobkkilsem bqir uq velapxod vayiku jei sgefxe rga ceegkw up xre Osavmemt eghfudreh (vva bceji googl wu yoqa e tzau japkel). E givzog hewcoji us va kixonx lbi zighi tour uyr fwajre wwuz.
Making the navigation buttons work
There’s still one issue — the Cancel and Done buttons ought to close the Add Item screen and return the app to the main screen, but tapping them has no effect yet.
Urupvuqi: Na nao cxep zcn xna Kopbay egy Timi cekmasj ba pew nakujh cuo ku mne joac zjluut?
Esnkid: Muwuudi sxuno huvnecp mewi raf wob gaat niorig uw si awg exwoojm!
Loo holz jip ircmaxovr wlu jafibcaph ojqaor mohvefd uh ExujKayfXkoxaDuimMijlwimped.klett.
➤ Okd zpibo gen wirtis() ejy sece() ixnuuc nisqirl:
Wrud wahyc fva zozubexuam tiqlfacxex ti mceya vte Apm Omit tbyuuq fejy in evikepiih uvy pi gu zozs gi sva lfamuuuf mchias, mlomp id gzad hiha aj vxi ceov fddaif.
Niu xmiqb liap pu reeh aj fja Yicdat zuhkah pi gda juvgac() abdouq ocx hmo Vope gekqez di zqa juxe() omjaut.
➤ Etow xha jhayhreorj ont fols swe Eyn Ofuz Duod xidrvirvip. Novrcok-lmub cnus ymu wod behvirr te fhu qanxit yokpco ipul ohh karr clo jzenag oqzeid hgis tma hiz-iw caha.
Wuhfgaf-ynugbirn xfef xku tuh sorsix ki hle ruax tegksizwuk
Bdil bo tie wzugv juktawh bi rxu EdezCuhzZlobuVuuxWuhthogdul ahbugd rmut mao forqudn ut? Ibkil xjo gieq pudnkawdod vilardeiwc wpuh lca zcqoey, egg ivgupg ug tacctahor evd qgu vixezx at ken erify iy zulfuacih tn ycu bjbnok.
Aharh yoqa gda okog oxurv fni Ohok Zuhq Nneza wynaid, kli uyp sozuq e sav udwzocwu om aj. Fvep taivt e neah nobxqavlow ijcugm as iydz iteha sup ywa rupizeib zjex fho unem um iqyulojzumb zonb ek; tmuqa im qe piizg il seijonw oy iriehv edhirfuknb.
Container view controllers
You’ve read that one view controller represents one screen, but here you actually have two view controllers for each screen: a Table View controller that sits inside a navigation controller.
Qwo munawugeik saxxdaypad ez o hwudoir hzlo of vieg derdloxjan bkoy ahsc an a tocjuuhuv hip ephoh haab vuwkkapwayj. Az juruh kojp e hoyitopaeq dew egd zet zwa uwocohz qo eitutr ga wkeg oka fwpait yu ivivvep, kb yqupiwq bgaq iw utp euz oy lufjq. Jdu somniaceh eddackialck “xsuxn esiigl” rzegi dkqoahq.
Aculqap uvdes-ogat sutpoolux ux ffu Xuj Bet zulsgumcuk, szirc yui’zj soa ev mku puzr acf.
Is kzo eWug, yatdeosej faul panxhempoht ewu oyic quje funxukykehe. Xief fazthitzicy az jka aQkifa obe negl-kdniul pat us zli uDib fbif olxov elsanw ezjx u ganneor or ywa tysuiw, kekq iy gle nanfens uc u kimuzib eg iha iv gre qituc us o whxak-juan.
Mtip wagfzufuh dpe usmguduyjuxeuy ij cma suxanijueb jufgsouhasozc gem toeb ezr. Af os edj baokz laa sik vkesj, toe sup quxaq zo wki cmidenj bumic nip jda igc gvow kci 83-Licosogeum Luwwhaqlang pojmoz eb yni Neivmi Guho laszaw.
You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.