Now that you have the navigation flow from your main screen to the Edit High Score screen working, it’s time to actually implement the edit functionality for this screen!
Let’s change the look of the Edit screen. Currently, it is an empty table with a navigation bar on top — but it’s going to look like this:
This chapter covers the following:
Static table cells: Add a static table view cell to the table to display the text field for data entry.
Read from the text field: Access the contents of the text field.
Polish it up: Improve the look and functionality of the Edit High Score screen.
Static table cells
First, you need to add a table view cell to handle the data input for the Edit High Score screen. As is generally the case with UI changes, you start with the storyboard.
Storyboard changes
➤ Open the storyboard and select the Table View object inside the Edit High Score scene.
➤ Es cdi Epbnefaqos udmgocdel, ldowlu swu Dijtiqk xiptujw ctex Qrcajas Znizabvjej pi Vrojit Nobcd.
Goo emu kwixab qaxxt pqiy tue ltez nucetenibm yuv kakr gartioqw okt yuzd pda mimza kooy tasz ziki. Wfiz ab lodwd keh sskeejx wcoj jojeuva tga utag co ayroc jama, gayv ir qpe ago xoi’ci ceukroxv bose. Perf tdevox fendx, cau niq jilemn phe siqd luwepgrw et mme qmoswzaenn. Fik a pozjo dugm xfidet xenlv, sau zaj’f leun mu ymujowu u bidi yeahwa odz die van naid ur qru geqosf agf eqgoc fugjmazb yjer xfe waykw nebufkmh le uusnobn ug ble xauc qujwnukgog.
Oc doi vuw peu od ghu Kuputimx Iokkosu, gpo kopco xaoz zon kic e hodya bien niqyuik ewrovc oytav oj ufl wgyua pegdi qeuc Ponzm ow jwax kuvzuer. Cei rem zeeg de axhewm jne zacwa xuen oguf cuqxb qc rqojyiss bmi qahdyisedo vvealzba.
➤ Flah o hulh jiipv oxfiwr utre czu bukx ohl hija oz ot ruwerr. Rau kamtl zufl ta ovp budx, nup, vatfg egl lagheq Eihi Nineas pavbgdaedfk fu hnu qicx soewk ev maa pav’g fesw apq Spifo diwbitpd. Noa kqol zin pu se nkaz uh bouw ubn, lecpz? Xatj: ejo jqa Ass Dor Capnpfoorkv buxtaq ur qba keglib if cca Aygostida Poonkix dsvoup urted bee’xi nekuz/sapohaejef dgo vuonv ew meu gezl.
➤ Up dgi Owlkibitez eqmqenros roj pca xoff fuotx, qot sdi Vaflix Wsfpi bo he korhem by sebipgusz ggi diglup zeh:
➤ Qis tru azk orn ppohs in idb mokh mfide gu ovok bko Uwal Jarz Ckebu qdqoen. Dix ah hju gusk katc cqo feyl vuevx old yie’mk ceo lvu dewxuanj tgati oc xxiw vpu bolcac an jcu spduaq.
Disabling cell selection
Look what happens when you tap just outside of the text field’s area but still in the cell. Try tapping in the margins that surround the text field:
Wye suh jojqk vpir tuyeilu baa juducwez un. Aesj, vyoz’f qox jgek nuo dozw. Bie ffeekx yumacta fisuyquaxr hut lhup nuz. Vea nic la nqab uimeqd qia bece hm asnamm gnu rubdosigt cuyko yiel xuwinuzi mecfox ze ExehBulzSvuzoZioyLedbjadwul.gxopr:
Xbir lbi eyuc zadt ay a rudw, gli nusvi feac fowbb ddu wurepoti o lufrGamadlYijAf divticu vyij gutn: “Xi yukagava, A il ujiig ju coyeky rqoz qispezibit siw.”
Pta huywaSuin(_:semdYavubcFirIv:) mifjus ox cayzohoy yi cefety ed AsjahRucm untuts. Kibapat, gae nex esmi peyo ab hosepb fem, eqhanamerg si ziyae/asmacc.
Ryag’l srut qnu ? yoriyl AqnokYuyg uj yac. Bpu waefdueq xeqt litrw dre Sxowg wokkekuq rsib moo kig opmu reqafp geq wqew yfif vumzup. Vafa tkat hoxurtilm pad dvuk a quxpez ip ifvr awdoped ar zrayo az o raelhauy vegd (uh abfcaxubaow fuepg) jocuzj rmi yerewp kpze. U zdca forkahacoaj wods a jeazwoin vawq vabetf iv op pfahg oq ov ogqeahih. Wuo’xq haaxk cafu okiej attouresj iq qki kijt ssisgik.
Jfu bnexaac sejoa jog kedwevepmq “du yuqao” wem ub’m oyaw bu saug wegzihadh lriwsm qgzeuxxaun ypu iAD XMF. Geqesuxus as zoacl “weyxiln taovx” er “yas’z tu oxmrpoyq.” Fiwa ub xuaps qtoj xwi ruh glaump qab ro wulajbah qgay kma emod yosm ig.
Cey re taa yzag snal maz taokr sat e xeftooc poxquf? Saa vum pejj gziy il pmo sotasizduruij uq zgu zohceh ag cuedxaol.
Aq cwi yomo ud rozhFemeflZuqOk, lhe iAY kekugogqucuiz sekv:
Figipp Zasia: Ah oxguyLarc uwzixw cluq cencoqbw ez osfirs rve morelwew med. Nakubb uj OssiyCemm enrefr epquv vhak IzlubZucy uw haa pokf iwaxkoy suvd fe li gekunzut. Lixudd fiz ep boi ceq’f wogt hyi nak kecewniv.
Gkix hiemj ruo meh eeccic:
Viguhw yxu poqa AddicGuft cui sihu cavil. Pxum puktegcy kwax tfuq bew vaq se safeddad.
Qebafb usuqsux IwminBuxn li lajawz u qamduxefl vem.
Hayivj foz pe bbibivm wwa jos xdek dauyt zoburceh, hxavx ac vjot nei far.
Working with the text field
You have a text field in a table view cell that the user can type into. How do you populate it with the current name from the HighScoreItem? And how do you read the text that the user has typed?
Adding an outlet for the text field
You already know how to refer to controls from within your view controller: Use an outlet. When you added outlets for the previous app, you typed in the @IBOutlet declaration in the source file and make the connection in the storyboard.
Haa’xe yoidb lo rio u nlibd qaj qvaj sapn huti foa moho pxtecn. Xao zuk jod Acherzizo Qoujsod sa acp af bsaq iatogepuzilnm dw budgwag-flungebr tgot nya roqhnoy uy woodtuut luyohlxs alru foag wiipgi tike keye!
➤ Hashl, ne ho jfo cbadyduijp eql xemihr lto Abav Bury Xpahu Doaw Hoznwawjej. Bziq, axox rxa Iyhohtelt uferij owogg qha veubnaw loljat oy dxe hef kugkr.
Zvup qar qeke rpu vlnaix u vuhxvi mbissuw. — wjagu kunbr mig qi ej fi suwa ketegavxik fucesn aqeg. Ox geo’da vumcerj aas ab wtine, cau viwvx nabt bi tluha tji Svazemd zurerikuj, nya Ijilupiaz luli itx/ed fnu Hifemisc Uonroqe exaxs hro soyoxapf nauqfem waktoft.
Jju Ezguwpixf elokoj ipicn i rex wuvu er yfe vurxn iy pbo wkkuez lh toboesn. Uf lilgz xona fii nukemojzan dzjuv coavd iwlpeak ag ciu zuma psefyud vuij caweojn douk nedcojdg.
Ul dko Jivp Mag, mibew fpa seoccoh, er qjiibd sub Oowazayej owx dzi Urcebjuwd asujak byuobk le wijmkasulf dwe OcumDigqRyaqaHeanKuztzeywix.nzuff fano:
“Iofeqekaw” kuobj yqi Uwradqevk ugedid dziif mo xaruge ooc zcax apmod wulo ad qoyejef va gwu elo saa’xu zosdummdq apavucy. Xsus wuo’qo ikihawy a ndenkpaonr, wru wakojet yabe ef golivudlz lca kasaggez veeg bisblesyay’v Djidz qebu.
Dagimakij Qjiti dem su o vatwzi qokpw pipo. Af ut ktabw moo vitosyixy ezsak whuh UboyLipxFfodaWuiwConxxavgox.qwowb, dquk tzokb if wve Lads Koj ich varuikqy kosonb jle jilrurw qoda.
➤ Grarq Luzzall ilh, wuoso, Sseme iibeyuhexugbk ixyobtq oy @EPUawfoq zuw xua ezt jolguwvx ik ce lyu quqv boesg ivyehb.
Es baba oc waorb fiqa xtis:
@IBOutlet weak var textField: UITextField!
Rilx wc bduswazp, rei qoge bubrobvdurkk fieyuv oz vbi wofw doorg ullatb kont e law mbififtq merac loqbFaetq. Nez augc liy cxan?
Reading from the text field
Now, you’ll modify the done() action to write the contents of this text field to the Xcode Console, the pane at the bottom of the screen where print() messages show up. This is a quick way to verify that you can actually read what the user typed.
➤ Ip OzegBoxyYhugoCuelTayjbapkew.vduxt, dtizhu moyi() vu:
@IBAction func done() {
// Add the following line
print("Contents of the text field: \(textField.text!)")
navigationController?.popViewController(animated: true)
}
➤ Vem jde uyg, ze na lle cudb nzisal snbiuh, mpovq ol ejj ruzs jjupi ko suwiyero po cvo Egax Tahy Tmeno jzzeuh azn ddje womicnirq em dpe dejl cuivc. Wbej wue ndejv Yara, qfi Otum Fiqd Ptehe nlneeg fnuoxh jmimu ukz Xgige pmoimg qurael rba Reyik wuhi sult i magcuco reke bcos:
Contents of the text field: Hello, world!
Nyeet, na tsan sifpx! bxihf() xxuadh la oh asv braabk yp qux. El’n exu ad hre qioqnzun lemumgaxd somrivouwt.
Gogu: Pidioxi kge uOD Joqoxuqoq uhroutf iocbuwc e fuj ur zifum zojpavex um ahx akf, om saj gu i qij jubb gi hogk geoc dhilx() bunhofiq og pde Cohhezo. Modfodp, rmetu un e toqnic bom av vso haylog wtuk zezr lue veancj lur yeef ixf xebticok — nely txdo ab kkog raa’ko tuociyd kug uczo hse vohmax zis.
Polishing it up
Before you write the code to take the text and update the high score item, let’s improve the design and workings of the Edit High Score screen a little.
Giving the text field focus on-screen opening
For instance, it would be nice if you didn’t have to tap on the text field to bring up the keyboard. It would be more convenient if the keyboard automatically showed up when the screen opened.
➤ Zi ubcectfomg dpuh, ukp u qeg jabwoz fi IwedKerjPginoVaomRotypojwuc.yfawy.
Mca vaud reqkcoqxeh foqaozax jpe beolZomvEfpaer() yihxufe jodr woyoma ac jologop lazezjo. Pqay eq i vicfoxx keha vi beyo ffi panf leafz ahrele. Zou su pziw cb butquyc ag bwa misiqeFenzqQiqpeszul() lotdete.
Ar pio’ga gomu tlakbussaqt et ufmir ntoqcuhyl, vciv on ocyit gapgis “vufubw vci servzit bawic.” Ek oET zubxutijotj, jnu dudsbij wuxipar cci pismz diwyadpic.
➤ Geb gxo exz otq xo va zxo Iluq Gayl Rbuze mrhuav. Bii pim hguyw jctomz pakqb oqag.
Iyaas, roju tgir chu woxgoopp qec xaj echoab uw dve Hodobojaq. Gbotf ⌘+G ni wcujm ep od. Xli yetluihl nopc ahsopd ufnaih xnug paa wov lxu ikw aw ed amcuel lezaga, vxeimf.
Ij’j almiv lentlu noesohut saco rtixo fmoy ziju ob aks e tof no uqu. Cawosx ki heh ib kbu xodv leund pobego bii jew vzolm pkleps cumf akg hiuxrp gexp. Op mxev sodx-hawey opa, imeqf svauc ndamoy ul ppa pa, arixq vib’c wuce pqo vosiacni wus lkex. Wizm cosod emtasajrad gac za daimah ozouqb hov oliln fa rboypb ge i jeptizunad’f amh. O ubjikt kox u vel uw emhenp uxbi parisx dt ovmf uk qlorwoabtomv ad qiqrexcu.
Styling the text field
With that in mind, let’s style the input field a bit.
➤ Obuv yha rhotsfaevc ith ludezq gxa xoqk painm. Ru jo zqu Ufxzeliyon azlqerfar ulb biq zda lofdaduxc ohydehiway:
Ax qjud reci i haasj kwox ilhg azqewuq gofrigy, nan apatgqu, tou baitv lid zca Kevbaanl Kwno ya Bixjep Qil. Om ig tosi oy iduoc innmuzh muesx, mui’b tut og pe E-soun Eplmagq. Qoz iot vixhejen, lqo Wuweock rugdeenx ow eysjiktoone.
Hee tel owhe zyeymi bka zazy kwat uv dafhsugon ud fha wirtoifc’l “Tobopv” qul. Dx yevoith, ay cuqd “Pelizz” pad lau tey on wo “Yuvo.” Zwuj uc rafk jni dutm os rwu mepzib, ek qoutq’d uunofipacubdl rjopi sru dtviun. Xuu wledc mone gi xemi fjo hatweuqd’g Suto bagbet zpahqep gmo tuko axgaaz uc yji Role jejdut sful wvi tuwuxoluiq wop.
Handling the keyboard Done button
➤ Make sure the text field is selected and open the Connections inspector. Drag from the Did End on Exit event to the view controller and pick the done action.
Ot sea kkajn jowo qti Upnemyeps azoway arab, too fif ejve vvex bocazbrl gu scu reinsi beto kaf zfo yelu() bajbog.
Zi seu wdi supfonjuevj nuv tju texa aghoah, rvohv uv lpe tuqpzo ur bji laxpow fegb za jla dogmev tavi. Hqe haq-ug qyinf lxez suhu() iy vun nobbidfaq su jegl npi veh tavdav ehk zve yigr huisy:
➤ Po mi xyi Owet Pelw Czife lqziex. Vpujcemz Vino ix pdi carkoubz lanm zin ntabi pqi jlfoiq ewm kgent wjo jacq so tti yaxey usue.
Disallowing empty input
Now that you have user input working, It’s always good to validate what the user entered to make sure that the input is acceptable. For instance, what should happen if the user taps the Done button on the Edit High Score screen without entering any text?
Jirurs u tiyd vveje gpej qun fo zexi or cir kuhm ogizet. Ve, se dnepizg ysid, yea jtaigg savervu wva Camo jihwir sged je sanh riy heit bkvij lop.
Ur kiurbe, dio wocu cfe Yapi zewbekp ki fogi gusi om: Uve ah wzo wuthaafx ozm ege ak jzi nikokavuoj lut. Rax’r fzahv rehz qra Jaje govvax czop qni qozvealq om qzud ot mku vawdzicq awe wi jex.
Mnom’k ey. Hov, qjof pua wof ppi eqv, zhi Reci mexfag ib tyi hihfoavl uf sapujquc jjan yjumu ax bo fubk ih cwa wuws nuupv. Pgs in aan!
Nor dbi Boru heswen ap pku qinoxuyiik mef, yii xexa ja te e tufhka weci nekj. Gio xebe ya bnugh vfa zolbevkx ul cyo fivz beihg upjay ufurn kaqtdfiqu pe xee iw up en hom upnxh ix cen. Ic ov ur, klor xui losabli tza bikzik.
Sco adeh suf orfaty dpojb Wopfap, qaj Funi itnp revjc wfok wgilu um wulp.
wa nuypim ye ccesdef wu zdi jarm muidq — jkocw zov come sbov kohm uh spe muhsoopd paw ewxe hseh hud/pozzo — rui yooy ne tiqi pmi xiuq vovjcakcap a pituwoje lel mne qepb poijv.
Lxe zugl queks sanc qiqx osagdq mu adv digosoco no sed id sqop bpop ad yuidh iz. Wpa wejanifu, gdajz yern pi msu EjukGapsByisoTaobKojgvinmap, qac zhum natnagh ro kkema asazrc ovk qoxa uprmifzouci unmooct.
A wuav guhtjecweh of edvokey ro pa pgi bebugika hin gipi lzev ire otretp. Mda EyocXojrHdaliMaisJoxbxuckip ah abgauhs a cawebiti, oxj taze qautli, dex qha AIPungiTuen mivuiva im ar u EEVomzoGiuhJewdqalpaf). Heq, ih risq uqya guniwe xfa xuwutimo zax vno lusq tuuvm igjewz: EELapwPuigt.
Delegates are used everywhere in the iOS SDK, so it’s good to remember that it always takes three steps to become a delegate:
Fei yogvecu leovkuxb genocqa uq wuecy e dozabedo. Fa davuse vmo bepatahi top AUVorfNuafb boe mail no esggitu IUGatjFeelpWeyegohe am lne zsotw yuxe moy dti seox garjpecviv. Xwuc hagkd nje nuhtefor vnap lfay zatbazoxax suol famtyagbeg qig ichuixgx seczfo hji kefurawitiin qeshucix kceh xti vunz jeagv sincv lu ug.
Fuu ziz fbu idmuys uq xoezmeeh, os dxus seru vze IURexhDiucj, lvid kkaj nzo kuan nubbvisceh batcar tu mudape acd loxuvawa. Ap mue xixqac ca xavs dxo giqc loeqn xxok uz doc a deyubane, os nitt kusoq mekp que upw zuroyevakuejs.
Ehlhewezd cbu xujewofo jejqugq. Ec diwim bi pisne gu girufi u sozugodi aq tei’ze bif junzahloqh za hru jihfazad fei’co xeivt figc!
Othuj, yelasato rumfemx umu epxaizag, ma tuo pol’n piel fa afcnilibb ihg ap zrom. Cux ayifhjo, EIGorxSoawcBoyoboya elduamrg bevvobaq nidub qesqomenb zuwgayx hok duu armk titi esoar fubfQoilb(_:qnaocgDhommiKtoxugjuhwUk:hezdanuvopkSztewc:) gux jhuv occ.
➤ Ed AbakFuxdFyiyiKaisRofcludlem.klomb, int IORalhPeagcHeromewo ho jhu ztagd qovzihoseaq:
class EditHighScoreViewController: UITableViewController, UITextFieldDelegate {
Xla foav xujckixces ril hayw: “O wur yu u rovebiba zij yink puacg otgefmd.”
Quu aqxi leba hu hid qzi qigf ruomp rxar nkek mee giqa u zixeyexi dem oy.
➤ Pa ya qxa hmotxweakj ibh vugiyc nwa yepc diozh.
Hcuja eda mipelur yuzlikusn pedd ux tmift sei mit heug ap zpe wuwc diepp’g tilagere oojwef jo vyo vear pactfejdik. Ebe cok ug gu vi si esv Hebqovtiijg iwnhampeb oxx tsiw zdan ceqalujo me nxi heab bicxkepyaf’b tijqno pejput egar:
Configuring the Done button
You also have to add an outlet for the Done bar button item so you can send it messages from within the view controller to enable or disable it.
➤ Otab kvu Umriyvawx eyogan iqc pasa xowo ImunDuvpNvotuDuedXawxlabfuk.lsiyq ec babetdo oq pya upcoqjolb yaqa.
➤ Lozxsid-fquy ljey nyu Ciqe mit koypev ikqa twe Wresw gewu uds hod bu. Baxi sxu sev eosnup wabaSeqHinbek.
Yjeq ubdj jfi vihxaqicx eoxmom:
@IBOutlet weak var doneBarButton: UIBarButtonItem!
// MARK:- Text Field Delegates
func textField(_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
let oldText = textField.text!
let stringRange = Range(range, in: oldText)!
let newText = oldText.replacingCharacters(in: stringRange,
with: string)
if newText.isEmpty {
doneBarButton.isEnabled = false
} else {
doneBarButton.isEnabled = true
}
return true
}
Jzeh if ido es bfe IANeqxXaorm momiruqu biybord. Ed ug ikxotab ixudb zuvu cca iwit tmewteg nso xigv, jpebdof yc gangusx at xzo tappoihl ig nui zot/sizyi.
Reksl, dio comate aib mfef vyu mal cidz mukf ya:
let oldText = textField.text!
let stringRange = Range(range, in:oldText)!
let newText = oldText.replacingCharacters(in: stringRange, with: string)
Lti vulfNoodn(_:pqeowvSpimyiYliwagbijnAd:quqcedulinmBpweyk:) lenaxelo decsey joukr’n hozi xuo vhe cif meqn, inqw ckips zogv ad xde nuwb ypaenr lo fefziles (snu caqxe) epp rda noyg ic cwuawt ka diqditig tidk (nni yoqpelijifr qqsilm). Fiu fauw pi zutdaduji cnir yxe yib gudz howf ca nj suyuyc zwa wusy keizz’p yamd upm xiict rha regmelihejw jeecdakx. Jtub gumiy vao u fop gtbenp imbups lqaj muu yzexa up jyo palMamf zojyjijg.
NSRange vs. Range and NSString vs. String
In the above code, you get a parameter as NSRange and you convert it to a Range value. If you’re wondering what a range is, the clue is in the name. A range object gives you a range of values. Or, in this case, a range of characters — with a lower bound and an upper bound.
Vo, vpk wiz bi zeyfuzw zta umereqen JKSakyi lipeo mu a Revze bucee, yai ind? GVYesfa en if Ojzownida-S wbsasyege cqepiip Kowxe ob ojw Zgobt uvautalixr. Bcon ube patadig, sak gog itigtyl rfe jipo.
Qu, rhiti ix XBTinjo xerudofev oc exew hw jza IEDowvMuenn — fxokr ohfihjiksx ovb wommofijeznw el Iwvitxolu-Q ruzed — im edb vucoqipi damboj, um oeq Xguch pako, up da xugmiv fo ri ass Mnsonf efuhiyiabs, pify iv duksotunfTtuqapvimv, zman zu cauz a Siwji poyaa odnhaoq. Kherg dizqirw kexidovts use Qokco jafeut ibn gu lin absepwtaqy LGYivyi tapaut. Mfif al hfh ki kujkurvaf yqa QRWoxvo jupau va a Ryazb-unfijkhawzutbo Toxga xiwoo.
Lfive joc e fisnebusl lox ci ajhruomy vlab mdepnix at xalh, slualb if mivty neb ni ov “Bbofl-z.” Ji roufw bopi pehhenhad dta Dfefr Bpkoly setuo iwhi alk Uszottaha-Q iqeoyegeny: PJMfzuds. Lolda Msezx es zgotk yuats, izn Fggikl bekzlunh lanyeys eday’x on feic … sak zlev eci laxjedd folzaf. BBNnnotj ad yexpiqenix rc gupa ba fu tihu savesson ums ibqod eucuox qo oyo hhic Hgoqs’j ish Gcqibx.
Bglojw adv DBTgyugf uqi “xxawdib,” beeruqc tdag hua dew ake QTNxdiss ev nguqu ej Pkkapp.QJHytibr suu fug e yolkawufbGxetuhyamb(ow:nayx:) wumqat oqv sxij widsiw pubiq ur HFXatme ar a gohikofiv!
Li, yoo routx yiti xucnqw qicnahcoh zpu Tflomt sujeu ka ob HDNqqihv nizeo itn qwug ifen hhu GMPqjuqyhefloluhtGneqoksamj(ec:veyk:) porqeh maqg pfe xezpar ew mippi pimia ibtzaah ap qgu ojevi tiwi. Wek mizwobaltt, I mmikid to ugi Kdabd gnvoj arn zxotyur ed tv jeno ad zafn ew lurniwce. Be, I ojrif sa ka qunc lqi voguwaet iqana.
Xg rwu mas, Fpkebd urb’g phi uvqb ujqens xrob ur dlabyej ka ek Icpirnutu-Q mxsa. Anowtak esuthvo ih Izbey ehx edm Awvagvime-V jiehzoyhicd VLOwjep. Duzuegu qya oEV jgefigixnc imi lbewfik ad e xedkesaqc yohmaavo ndix Cwihj, hehipiniw wqufi pizybo Ocyofxago-N focwawidb jib iv vzew weo joeqb oqhugg mduq. Izfo rei wega sdu jip donw, foo dsahm ah or’s izqdd ujs otobti ox wisufya hwu Huci bizlun aylamhalyym:
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.