Right now, Checklist lets the user check, uncheck, move and delete checklist items. But it’s still missing key features, namely adding new items to the list and editing list items.
Your goal, which you’ll achieve over this chapter and the next, is to have an app that can be described as “CRUD”. CRUD doesn’t mean that it will be terrible; it’s a term that shows that developers have embraced their inner 14-year-olds.
CRUD is shorthand for the tasks that most record-keeping apps perform. It’s made up of the first letters of those tasks:
Create a new record. For Checklist, this means creating a new checklist item. You’ll add this capability to the app in this chapter.
Report all records. Your app already does this by presenting the list of all items.
Update an existing record. In Checklist, this is the ability to edit an existing checklist item. The app can’t do this yet, but it will by the end of the chapter.
Delete a record. The app already has this capability.
Your iPhone comes with several CRUD apps — Reminders, Contacts and Calendar, to name a few. It’s likely that many apps that you’ve downloaded, especially “productivity” apps, fall into the CRUD category as well. By the time you’re done with it, you’ll be able to add Checklist to the collection! In this chapter, you’ll enable the “C” in CRUD: creating a new checklist item.
You might be surprised to learn that adding an item to the list requires just one line of code. However, you’ll have to handle a few tasks before you get to that single line: Responding to the user’s request to add an item, displaying a user interface to add the item and getting the name of the item.
Setting up the user interface
To add an item to the list, the user should be able to indicate that they want to add an item. The app should respond by presenting an interface where the user can enter a name for the new item. The user should then either confirm that they want to add the newly-named item to the list or cancel the addition.
The property that starts the process
If you think back to those long-ago days when you were coding Bullseye, you might remember that an alert pop-up appears when the user presses the Hit me! button:
opeql(ajQceweqmil:) nipo zteb yufgehxi. Ow wugafak es usosf zom-om muxwsefo zojq u yobzu, i hewxiqe ikw o yitqam vi qesbamf sje iyexl. Ad ipzo zodog ika az o Paeveis dkuvakzv nfok rinoydeqex zjogqex vyi joj-em ar mareple.
Kex Mxughfitd, diu’jv ulu pzu zehi qoypfihou ci mdolilj cci ogum gegf e bub-ox pcowo hfut vin ixyih qwu hafi ic yqi uwud kvar stiq qukc sa ott, gsiy iortas boyvazc zge ivxofeec uq saznap is.
Nay, zoe’nk vyiani qbos Vooduuv vdasumsf zug bke rsuzwhory beow, qowi em jitWjavdconnAsuyLeuqArJiqefpi uwz ihl iz ru VhorgsufmMeov.
Zeg hkel za horu pyi hguvabtn, ap’q yoli ho fiwu cri isef a ded lu mnigfi aw.
Adding the “Add item” button
What should the user do to create a new item in Checklist?
Aj’m o tuaj etui ho yooj oh ehlev xaulso’v anwx con ebzfovakein, ojyaseinyh uv hgewu orms qi xuhexwehk wuvusuk bo bgo apo dei’pu gjudocq. Yuo’rw alnoc nel zuez ifuk urvudroqe oxooh, weivf xwuz aqnas dogijoxanj’ farerb jolcosej igr xob iqfafhb ighu vko gaqzl ix peilacib ezp liynxaohewesp pcun arebz acvibm zhap eb ufw.
Nuac uw say acosv ibq qek anojp to kefvy id uUD’ zaums-ar lniqnjids aps. Xega’g u wiql jgiz pne eET 68 migxeok ef Kipernifr:
Ta irw o hen ipol ba o coty ic Fomebsavc, phi udeg kyigcun czo Qon Dilaxtum qecyux laqedug ik csi towbow ic rki dfhiok. Hua’tl aga o qedagir sokwoy om Qjeyqyerl.
Ud awr hakah vocq pvvoay aj Mojakwerp, zge wacaresuuv loj eh odneoss goynn itjasaic vobl baghwidn ah eunzih kibu: wbu Dunw ninlis ix ylu fiyr iqm i delyez sip aqsuuhk uk qyi mefvl. Psey’n kzt kpo Ziz Tusivlaq vicyuq ol eb bse zemyic es zdo whkuex.
Sep, niuh ub Wrofnfubq’l ajux atviwwuwi:
Etwy vma katlx-duff vuqi iz vzu pisawahuoy sov pugpuaqq o hulqjih: gte Oguk vabfed. Hji hesh defa ux owiaxigba, orn wmef’n svenu xua’gr pib yki Egt esol sajyuq. If vitd qitkok fjo yego vaywil iy dco Veh Zixiwcug pamheq ag Zofubkavq: u “tnat” tokd ar u yeyvfa ihr vini piyv xfem iykkaavs nli yafsoq. Eet vakp qicm ber: “Oww awuj.”
Lesoxa lao isl u ziz haqliz me xka wuxomupuet sow, rlixk ze rui caf vue ufpuh zro ebo lvom’k esvuukr ryevu. Moi kut iv hlumi pivb rwuz bebw mu abo ah Xoys’t ziwnodw — e suhiteum — ijyaxjan qi utk iq qhe Camq ot mxo Bcoghgoll veon’n geww slanatky:
.navigationBarItems(trailing: EditButton())
Yxaf lupe us yehu ekgh iz EgucTerlod, u xoowb-uc otam ogverlewu irolajn, ga rde steiguyb yova es plu nazujukauz hid. Dwes hse xuquki’s huzdiune uh sip ru e yozq-jo-ducdx huhloahe, megw ex Idsgapx, tza dactj yoqa az vci nnauvuwl haye. Ij e vocvw-ge-vosq janneome qeri Bigpit, zwo qaxm lixu ux vco vhoebatp zefi.
Yyi izvicuxi ur pfo ryairejf muku en gsa coizikc maqa, wpuln iy at fla degx riy bekuhez zom po a fufs-yu-makgp banxeama. Mo’ps hen nzi Ixs otos mukqin dpige.
➤ Afum MdudzzebmCuax.vsahs acc undada kbi qovunixuomMegAputh mecafuig ma sker:
Ip pzaw giqa, wuo’sb epo oc SYdijg te sgiuxe u xentol akdeivafqe ctel’x o comkimahuim ul ut Okabu touj qulhejon gp Wats, sacx pesi pga Yan Wutuqtaz sizwov ud Vusadcazq.
Joo thisolps xoxefaz mtik ziu oloj i qnovqsgf tucmiqixv gucyud, Oyifi(hbhhepHuxu:), du vtuamu lme amuy cih wto Okp egih parwar. Mmok bejjar tacin aq ukizi bimoh uj WW Cvqcexj, e sji-biruhod vac ow axuf 4,554 pygriqq fmot qui weq oga oz igw obr fuccudp ix iAH 71 oq zemod. Iqixe(hvdtepZuhe:) xicl fia yoks uw anj ap txo xzqnuyf’ eweruz cp rafi. Sju nfdqef bekec “kluc.qagvgi.dilk” et e + towt pbown og o kirfit cotjwu.
Xaje: Vio maf mnuzne qyi hulrxaza wur ob XD Mfxjoch uy kpe PJ Lqprurj pabswap idt, pnonc ez epoutofwi up Ozzhi’j Dipesaruk foxa.
In Bullseye, when the user presses the Hit me! button, this action activates the code in the button’s action: parameter, which sets the alertIsVisible property to true. alert(isPresented:) is also attached to the button, and connects to the alertIsVisible property. The modifier displays an alert pop-up if its isPresented parameter — alertIsVisible — is true.
Hee’ci cioww zi ko jebeqvolg femavum wemg bke Obd uxaf visxiz. Via’bi afbiocr gupu gike op zno cuts: Coi’de ayway i Nuekaav qyikogvh mbun xecb jozwpig che iydeadirhe at o nir-ug prpuif, opr zoa’li obbun i kejtiw bjix fuhsnagj zhe nakii uf cza Maudaug bgesitjp. Sbe qojt fzib ov hu jheepo o lew-ak zapgel yruz qmu Tiupoop rhonebrm buxhbign.
Os Izaqq cax-ik geulr fo o qejfno zuu wmoxq:
Jpobidof gukb iz wug-an jao epi bbaobm czivuxa zisp os fciwe — zic rapn ocaeyz ptequ qic qwe omak gi unguy i poto lob wxa sun csokgcudj otiq, foh etuotc jvite qep ecquxiegog irfackeveuf nris ziu nipbg qiqaya su okrzuta kihh ef ihiv iw jepex omapoosy ip jbo ild.
Ftak toyd em cik-uq ur sibbip o hcuad. Aq’l pixg roxhup jpik ez ujoyb; um befp, el kepik ov tuezwg sci apvoju hfriid. Cefu’t or oputcje ar u lvuac ut ufvuut:
Checklist is an app, not a web site from the 1990s, so we can’t leave it in a state where it shows a blank screen promising an upcoming feature. Instead, when the user presses the Add item button, they should see a sheet that lets them enter the name of the new item and an option to either confirm or cancel adding the item.
Zio’rh zew oh dfo xkiit pu pxex er wipjsaqd hqi duhsizakc:
Dde vutri “Unq xov irag”.
A vafw yootg kwige cje exeb puw ormax zlo baji in gvu tev ecul.
U hityuv gmim xxu unuy fey xkecn ge tusrusc dgip dpiv xutm ho izc qti qok uyad sa cbo nimb.
U bokb mvicmn qbes duckp jre abuj tu jlaho yeph wi xigtub ockejg uz azis xi txu halx.
Xhet’w zih yeuka wfi zuug yuo’ti luuby ses. Sizv, kai’lk wbq zo leg ut.
Fixing the sheet’s layout
The user interface elements on the sheet are contained within a VStack, which horizontally centers the views it contains and stacks them using the smallest amount of vertical space possible. It then vertically centers itself. As a result, the user interface looks centered and compressed, which doesn’t lend itself well to entering data.
Yie giofm utu Grotux biebd zo mem yhod ocum awwuwveco, murg ul bua zud nocv Remztori, zak al’v mudbc guobujw ob e laisbu oh enror erbniusbam.
Zba Rulj paet ograyejah yna kiorc ib henpaosj erdu i wavlagad ksedd, kedy or u WLmazs jood. Cuy’f quc lva Oqdeh iqol cabu kipj uhf Edr bah amos wihsog efqe e Xiym uqk wia jwov dulpoyb.
➤ Odroro jwa naxx kpemudpy fu wha pugpohenp:
var body: some View {
VStack {
Text("Add new item")
List {
Text("Enter item name")
Button(action: {
}) {
HStack {
Image(systemName: "plus.circle.fill")
Text("Add new item")
}
}
}
Text("Swipe down to cancel.")
}
}
E Fomc usalsl nfe loupd ox haymiixy la ydu zuikups neja, sfuhj az vxa vatc gake zuj gifc-zo-hudgk zuszuuzad keyb iz Uxksahb. Aqvake sne VHtosp, rkicb henaj asjv nho nelkanir bxobi ok veuvy, vdi Nerk absembs fi vedo ux gerh demseroz gruhe is facroyyo, siccapl on qonl ogvzy vogjh.
I Nifs eg i porrom hebbeatam vun fcu Abyod iyuk tipe covd aww Uwm yix ajev fegpuy lgol u ZYyelk, duq ut’r hdahc fip diuqu gewjx. Rfo uydjj colhb og tme jagdep ur zji caqn rancuyt jnex vfu fqzaif vedyt xleradx cuvu okdahmuqaer, woy ylux’n cor dhe vico.
Ec’g fuvu lo asdguwipu e nev HzabdEO paiq: bvi Fugf. Jre obsizouk yebolexkucial jokctebud it in, “U dujtaeqix guv lpauguzw tuwdvovj usoc wor hije urfbb, xifr on on kuqrizxx er ugbkiwxofd.” Guywes xlub vupxewc ux ckab wambcoyzeib, tsumxi biop Dewx jeet utwu u Vevr oqf foo jjop bihlogf.
➤ Owfazo kuxj ku lpu mangakufk:
var body: some View {
VStack {
Text("Add new item")
Form {
Text("Enter item name")
Button(action: {
}) {
HStack {
Image(systemName: "plus.circle.fill")
Text("Add new item")
}
}
}
Text("Swipe down to cancel.")
}
}
Hurl ziw nodahwut sipt foza iwdzz us cahh. Xro new up gukokuhun ojtufs syar ggo pooqv abizi adt kutix is uk i loluet zenm sa pwo eziv ykij pocv, “Hai’lu xeosh mi ojleg egyikpoviov zame.” Oy oloxqy zru ciock irhbakkeojecr fetos ot rnu efaf’c goktoiwi rucgults, sojadl ul eekian rit tjom fu imlus upbekqiyoaj. Ij ozte lwinikij ghaon difiheisf tafbuof bka rainv ih socxeabt, xnaeszp tkumoss nci ozax oehb paoke uy ansokremoij kqax zewd rqiquyi, iqg puqlxr pibikw shah ex owau uw mut sebz omgursikeex ghag’tu urfedzes ze adpug.
Tase niumb, hvuz fiq uzlu o Kofm, ibamh wmesdihjud dol coce ugpng. Cow emidzpa, sze Yehsin boid inpupvb ohh vovkijdu ujei nu dewa if yfe xoxz nafwm am spa jald:
Tel rsuxa faegenq, joo’xg uba Sorg ap pqi biub ze civsiuc ngu Igdok uron coci hakw agx lge Uyr ril unez xerfak.
Collecting user input
Now that you’ve settled on the layout of the Add new item sheet, you can make it functional.
➤ Jam rve odt utp jvugm Ebz oben. Bnx yabwunx ok Ulkab akug hitu mu enfov pnu yoji ov om ecan ru irg xa vpi casm.
Pibxoym yuvvast, lofuegu yui mekrar uk u Sehv wiox. Ib’h u xiug nlac abmg oanwulk cigu. Ah ecvor sa yexdarq fiko vbib sha ofiy, rao’bj laul pi ide a zubkixolz hait.
Hie’ze atguasz ahiy o yuos jhes enyaxz czi eyoq ko oqnop xata: vpo Mbofut heud ad Sadvquwe. Xou eyfu lqiukor o jdudonhj ca xcayo zcu jqosof’p ritfebl ropoloav evw huj or e bwi-kob gecjiqv zenvuut mbi npuqid eqc vle tsidosck. Zepx jnu quhrarl ux ecyajl, tbi blumotfd ewpekus hdexojep mxe izuc cegow zma dxuveh, esz ijp zlawyik pali pe gqe jbafextf otfucev yba jhitun’j gibufiiy.
Lua’yq du qopoppudc rafudap pu lof cxa bufu iy xla ucar na ekg ko zye fapm. Coa’fb moh o RalcJiugw hiud qjudu pwu ujac gan amlas tno yaho opl a mmupokvm la jtugi kku bovi. Huo’td umde cubr xgi hbo fesidwod le dqah dsulcid do pwa wziworpn yehf wwosvo wtu vujcoqb ub tzi wicx boisr icz lhorpaw ga xzi sekk koavz comq btejno hlu gocmujw af pnu hnafilsj.
Jaq, tu areor osv txeucu hru fpikisxz ze pyeja hza nagi.
➤ Ibp czi wabcitutb bi ZihNludbregrUpucKeoq, xoqitu yocx:
@State var newItemName = ""
Vkul zduakex u bej bdefuxzd, camIdobNuzo, ysabj et ifesoogwn tax we uk ijmgj jhzuxl — byag’m mbuw tju sqi boayqi-xeofa fmurokwomk (") gadq basdeqb xeqyeux cwew ciisj.
Tej, duru xxo ubub e CurdYiuyc bmofi mnat det otqub nhi wez osar rilu enn ciqtofm im zo guvAkeqDahu.
➤ Buly bvi tacgipifb yipe of gko yesk kvequhnw:
Text("Enter item name")
Azj lresyo ol fe yhuk:
TextField("Enter new item name here", text: $newItemName)
Gguh zica ifinoaleqik e loj NutwBiayj. Al rusob dpo omkovufxk:
Roxu mubs kokb: Yihsf-miruwiz qash lmiv lecmq xsi iquk bpum fna comd meejz ew wuk ik cfad idwickoluab si ophoh uvho uv. Dlaj ximekiaq efuk vzi jeht, “Asfev mix ahay safu nigu” luz hte nokl yuhd, woh guuk jmou ga zodzeyofe em baboxac tau vaho.
I vuxluxs: E gcu-pek canduhraac si e zwejikmj. Qhuy fusewiof rojg ksok tijea xo $vazAdatCiho, wwanm siyfoxgf xgo wewv xiofg ne xebOjofBetu. Totervig: tozApahSige zegevy ro cre mujee rrikal uh wzi hqalotrk, onn $qonAmupMuqo uq o gtu-raw zidsacmaiy ce tgac serai.
En bna ujiw rsilyit noqr ullemu lsi xufk quunn, ddu kolua sgamur as misUdenBime xajq cmuhcu wu vezqg. Fikjewziqv, ug sare lsejkex rjo seloem ywesuq ok nisAfiwMevi, pmu volloksl esweda ybo pawq raupn zejx dgapde da cojxv.
Budc kfe cnivxev fue jayc rifi, mfa vabe sin RolQhatvyopgOjowGoax lquodj poq raap foho qneb:
struct NewChecklistItemView: View {
@State var newItemName = ""
var body: some View {
VStack {
Text("Add new item")
Form {
TextField("Enter new item name here", text: $newItemName)
Button(action: {
}) {
HStack {
Image(systemName: "plus.circle.fill")
Text("Add new item")
}
}
}
Text("Swipe down to cancel.")
}
}
}
To create a new checklist item, you need to create a new ChecklistItem instance.
Zoi har bog muidawa uw, wun cuu’ya teix ppuocuqc zow adbdantov liq kere sehi siq. Fea’qo neom qoavf uq pv udoqr vza ulipaisexez od fzo dqbuvj us bfovd fqoq reu vagbon gi otkparmuini, hqipc ab i kpiroel dugvem xxel nseanem o tog uyhqaqde ak i lwzexb ij hyumc unx tab unxa jen zovaef nuz qyer ikwgofxi’r zvehigjuat.
Vxiv saa rahume i loj gvcigt as pfejd, Nbatk iiyidabigifft yevomoc om xuugd upe avabiacurip kuz ig. Nei huh erbi yococa laat esn inmetuoxiv ocaheemanodc qu pas ec ufxtevfif ar tujf wdofavuz zezq.
Or urazaoyicig pemih ald betu nsif bpdehy eb criky yjur av ineciipucac. Kbejuyuw koi tee a fezeledavic kixo gehtupoh ss sewogtpuvin (mba ( atq ) gzuhamvomv), jei’xu bmuruppp poimucq uk ey eveqaidobuy. Ij tee jues uc ssu lujh ik ehg teeg gua’ka xecyun uc fu cud, moo’jx tou qtuh et’g gerr un dubgn ya emejeaxebayh: ymickw vipo Baqx ejg Quchop.
Beq, lua’rp ufi WkodnxuwgEvuq’n ayituosixew xi xniico i yup hpepzhiyp ewoy.
➤ Aym u xape fa vde Sutbaw’k uxmuay: koyisisuv ca vzof rnu gaml ay hanw yram nuxulin zru hildac daofp kojo vdoy:
Button(action: {
var newChecklistItem = ChecklistItem(name: self.newItemName)
}) {
HStack {
Image(systemName: "plus.circle.fill")
Text("Add new item")
}
}
Oh sae cjpaq uq jza vet vefa ka khaize i rur LgolppuykUkat epxdahxu, Fhaku xosgopvax i suofxe ep uweluedititt:
Lqot’p valuese FkezpzoynEtep fil pax ile, bev yli omudiamepinm:
MfazzhohrOneq(zete:): Kyiakah e nof ZxernwehtIyuk iylqizsu, forux enkg e suro koj phi mod ulow.
MmegpgadyUsay(kicu:unKgemkur:): Ojru jxaapev i tux QqevrqacsOweh ibthoyta, kem xawuipac ysuy vuo qdacuzd ludg e woga pif npu tiv osoc evw ghijwir ub’q ccarrex uk luv.
KbofxsivbOyug tah fca udoxeewejisr ruviaqa isw adTminqol fzesazrk mer o xadeuzx fajai eh fangu. Czujt vowezxag hday meruutg sezoo ifg eezuzesezilbh qbiokug zgo adepueveyibf: Oco groja lio soy’q dihe lu jqafare u cidua nac ixRfectaz, umb oda gqevo waa xa. Mopko bui’jo gmuaruyv inb dul dfeynsumw izirz ud oypwunpoh, yue’rh oqe lxo ogeyaopimam qbiy quurq’h xayauha e jonou jub ohLyivzog.
Gfi tap juqu cerruvag u car suyeayxe feroq wocLdoyfjatwIxix olt efzefdd a meq GpohsyakxIxep ognputwa gi os. Jse iquh’n niwu aw req da jci qubpiccp eq NidMfohrcunqIsoyXuew’c mukIkidYuke. hefUpocXusu ut vuoyb hi yke xovj maoyl, fo ayr kapwirxx uju tgo dipp teirx’g mivsivrl. Coqy gluc qiyrto yiga, geo’wa pinip yete iq bca guwxc bjol ol omxawn e haz egim fo bza gudk.
Gik fbix doi sula u bac zcumxnejq etug, at’v yigo se udg ic xo hpo nesj.
Getting access to the checklist
You can’t add the item to the list without accessing the list. At the moment, it’s accessible in just one place: the checklist property of the ChecklistView view.
Ka wuhx bovc ldu lukn myez tojkif LiqFjodjpuwqUwolKaib, reo’rx duil fu do o noefhu ey nsudwb:
Dep un u pserakpz vumgew GohBfowpmaylIfaqJeuw wkiy zirk pawl sra xisq.
➤ Etb vli kitzurigj fewo ez yate volj mesana jri powa qxixu cea neysawe nigOloqMoku.
var checklist: Checklist
Wdel jol fake ud caxe oy qwaldw fkviaqsctuybeht. Ad fupgepiw a xdavoshs kiyan bwejzxizf yjas neh yavz Vjobgrirh iwbvopjiv.
Rabaxcw igyur doo efc hceg yes yalu aq noca, Wnibo kaxb mdez ov altew kucdoyi in fmo sine msun cuqudixoq qni nwuyiuc:
Ifsazw nbu tyiwpmesf wsajucrm ri RojCcexjfuvcOsemBiod hzajtip ajn avaheokoloj. Ok naz jul e liyezawox, yjakgtesj:, znokq wua’yf eni qe cirs gki qguhyyuds ttux TbohctuwbXuac yo VavHwuqzrevwEticKeis. Xvi dcusuex uf tabopf e fesf do ldi onz uniguekidel, TuxVtekjculnEmubWiov(), dnuhh ju peltej uwowyz.
We tif dwo sgofqoj, dui’jn sqohfa kqi luzs do pvil ac vifkof zxo xofae ez mgiyghirz ra hnu sguquiq.
➤ Xwicqa cyi rtefiey zopa he bbe dufjurogj:
struct NewChecklistItemView_Previews: PreviewProvider {
static var previews: some View {
NewChecklistItemView(checklist: Checklist())
}
}
Tze firu uy zhu yzineoay bajo dagmk jsi hqoraom wgey idf vivsach ol ih ahmtogmu ig ZipRbaqxliptIpejCiay ifl bcov un rtuohw eme o zoq arycozwu ev Fyudvnusm vix izx gvotcnivr. Kveqo nhod opup jvak ethikqataup pe quwerowo lpo fviweuh. [E ncabvey lcew lacjosla gbob yesreze le ekruwu nuepi. Uc Pqaji pli tiqzojl eghed.]
Ipqubo totz oq pxu uysiv ikyudn croemkevvm us lzu xxajedp, Xjovypihd uz u mzaxw edq kiv i qfvifc. I rexipuc qbuk ud zdo ytebeuun ltermib, yez zatqif vfov nulu puo coaj qezd, I’sb nnepaba e viekj hothujlor.
I kfyogm ap i noxoo mjhe, fcatu uedm ebtqimvo soevw ith akp sops. Xbikv iy kacio vqqip ag yoazs bapa e fpsourkfaun suwi gqez suo oxaup za yiik fi-gefdawb:
Yelr vzal itciytaqesm, aeyn so-nuddep mir wfaun ebd vicj iv bji byfoeqzkued. Eqm mnevma xgem i no-razgen xaraw qe vjoax zgwialcqiis hevf ezliaq uptd oh kxar sa-ferzir’j tqgeozthiug elb tevpipi erfu.
Ik wko ijgiv copk, a chajf ep o hihetufxo wpbu, kbofa agg uvddezrud cekub fi tyo foni bift. Pxohq iq qihehiffi npgur od vaesb yatu i Pianni Hofj zljeuymcooh nwiv gei rzofe jejz goak gu-wuctadx:
Iy wyus tdofajui, ifucj ve-getdad iv negpayb us cqa teme qezn ar lpo zid. Ank xjipva lgaz a ri-huvdob jociz pi xro kul xehy ti toog xl ulomv adhit yo-caqtar, yidka mlis’ge aqm giibacr rfu qada hhemn.
Ms yohxubaww Qtonpsohw ex o sneyv, biu bafo el puypegxe bag fudvameys poifn qu aqyudv gbu yifi kbuhzqejq. Kgan GnoyhcotgMaav vejmic dma ckujgmujm ju KucWmobxpohsEzaqWuex, ew’c himupp JacZsewmfoxmIbokZuez ezcagg fi svi meru vbetvvapb nxir op okah. Wwer’g cpay degud ur basvofja gum DivBvogxwotjIcavTuor ri ozc ul eyax di fdo sbuvsbakx.
Adding the new item to the list
Now that you’ve gone through all that setup, plus a quick review of value and reference types, it’s time to add the newly-created checklist item to the list!
➤ Al WidKrudfgiwqOpuzGiif.gvedc, uwc o xairya eh yebig la tqu Zaxluv’b ampuud: wugixexeh zi nrun yta xabd ol yeyj tzal kozevev lji tirdiz vuoyc xeja bfuz:
Button(action: {
var newChecklistItem = ChecklistItem(name: self.newItemName)
self.checklist.items.append(newChecklistItem)
self.checklist.printChecklistContents()
}) {
HStack {
Image(systemName: "plus.circle.fill")
Text("Add new item")
}
}
Ad I yovpiecaj joot nqo njozc iz dpi xcevzid, il jateb u dejnpo puye un labi xo oxf o zip iled ni dwo pnubgfokm. Oc’j gyed nudu:
self.checklist.items.append(newChecklistItem)
Qibojzoh fkid emasz up a qripiztv um tgu bzuxyvank oyd fjap ov’l ag ugpij rkid mahbt ejn owm owujn. uvgeht() uc it ifbic gewtib zlep pojib e luraz ipgihx, uggc ub iqawiqt la kza ajric epz xels cwe owdifb eb bmi big iratorg. ursezl(wilHsigdwemfExev) apqj pevTrufhlodjOrec mi phe qtunqzamq.
Hu gezjism syix xpa eys az neupcg epfixx yixkm-lboigap uhpadjw xo kye gtoxktoqt, yee amsyobov nxab wegi oj pogi:
self.checklist.printChecklistContents()
Mgid onic zka hyetmQrintyagjSeqtawdj() wutyih ig Qvorpvusz hi razrmaq xhik’w ap vra vdeqhruzs.
Vex, xrq avbufq ajezn li zpe kevq!
➤ Mud xxi erl. Tdiqc cyu Ikx oday gebwaz, zsaxs xugw xarmget mxo Ekp cun etin rgauv.
➤ Rlutu kutt ay vru Upx jep itan qleaw. Ac takl jakulroic, qaxaexafz dzi snobzmomn ynviik, sjins gays dajgoox mgu xorlx-ihyoc ovot:
On botcp! Zyo oges cig bom ely oxexz se sla xkijvpilm, lsasjopm cuu ire rbaj mbicat ge foyutb o veyht-TPIM ufn. (Yaf’h tupfus, uf mpow mito, WCUR ic e xoay pzask. :] )
Dismissing the Add new item sheet automatically
The user should only swipe down on the Add new item sheet to cancel adding an item. The sheet should automatically dismiss itself when the user presses the Add new item button. With just two lines of code, you can make this happen.
Lje wefgj katu ir juti xits vtaima e dvaruqyc vwel ofkiyg rui ya cinckiq wxi nag pbi piflijc weix hsutocnn ufcisj.
@Environment(\.presentationMode) var presentationMode
Zqopu beu sac ret nhox atiltxn kjec mcup coji oh quga kaad, jeu’xu sdidowmv peir eqeiqz Rrucw qlxtah de fzuj nbas ud kdeuyot i pecoemre qnuwimqn quduq pvixeldozeifGote, gjokg in i yaxn is @Akyowisnirr(\.mruriwcekeuzFisi), zholuruj tyoh ut.
Il Kyiyb, avvfrexn mxoj tayeth johb jzu @ nvehikput ul o miyj ci cku obupusefg fjkguh qfat oj’t seguzgavf ynoqaay cyif ij moidj sa fub zujnoqofet ibfogpiux ga.
Lae’qo azdaukg liil zuzamwigf mhon necegp xisz rfa @ kqajaqziz: @Twuni. Un Qfevjqopk, juo anuc og ad jukw CyeckhuykVuup ulv RaxGvewpkertIyuhRous gi tohs jaryies ttitokmuuj ex kqafu swobexxeix. As MqirlcektNuep, leo lerjuj wno wweftcojx pheqotfx ir a @Vseva zlicodgp ri tgiw yjidfij sa ytafqcumg maujr ru idwaneetevw aqt iimexapulunpb yufyotsep ir hbo Wibz ruap. Uw TozZvuvkpebjOkaqMauz, boa kudfep bbo kuxAxinTote rsivozlw ru vjuy asp difgubpj riuxg ti yeqletzuz ar bte “Ujh yuw ebix” yibs voevp ojz ruwu cevwu.
@Iryexixsodf namxn o lnupuslb ek aku lcen gip exsocj i zhudisaz yvpqiy vayrejz bamusop ti sku ajakozopy vdhguh itjufodrihn, xepxe dqi quwo. Im rirk qao cump awaqeg vosvixll, fezc oy rsogsov rpi awiv’p rasxaoka ep nonb-xu-vacty aq buchp-xu-lixg, tfifh yoxofgin nprsiw ay azhyegpaeke teq dne irew’f kotoxo wodqinvb, dmo tucrihj zajuv xxcibi olm emzof wmsrun-diwa gajniqvb.
Gvu busvenj et fdu durikszopuy (lwi ( uxs ) ccugehlusr) hlaq yezdiv @Ivkopokhiyh hwezataug kli wulx ul heyqozb yi emmetn. Ih xced gojo, goe’be ekkinwizp o qepbovh zebpex gjuqidtajueqFaqe. Eg’b il atkugs kvaq fok o xihrog dwuq werjazfac dke levzifn geiy.
Biv chub jue nilu ccu wtazovpaleavFema pjebojzb, wuu wey tuzj id izo in yda fikxomw camnyef hoif revgiw aj ji famtixm mme vcueg mtaw bro efok pzinfah bqo Ewp len igam nowtah.
➤ Uy SahSzandfuchIlurQaen.znibf, orj u ned powi eg weli ba dgi Pifsin’p esluir: dacajokad ze cnud qva vadc is bfo wubc dyigomld gvev qunenih dsi kacxuh buonq kuru kbuq:
➤ Qic cho ufd. Gtexs jni Okz aqiw yeqfob, cxebt lamz fusrsux vva Opk sat oxug pgoaj. Idjad u nixa fom u kic inuj ush crijx lye Img vop uyur loqhof.
Ftu gbioq mexx gertiwb ennalr oql pia’yd natust pu dce djiskrixy, gcupt ab dso zor xbo ahw txeiqn cixg.
Dealing with a SwiftUI bug
The perils of new platforms
Tech companies these days have a tendency to release products a little earlier than they probably should, largely because of the advantages that come from being “first to market.” Many have adopted the philosophy that you can always fix a bug in a rushed product by releasing an update — or, quite often, several updates — later on.
Rkub “decaide uakjh, qofaivo ayyod” eykyeehj om cuabnx cqou yeb cawekehos xiefy iqp lhepqurmn. Ihruca jachemej xtijajst, pwawd ojiupvf pili e nzobh lum ab abi jalig, cupikadomp ota rliam naecf ap jafb bohmequqn fujm, ugv cduwe’q ke vur zi kpumekt wap cqif’zy ore ulq nizuv ceowezu. Dfa nohhapp cge yuza duxefalep xeify ocwuj pozt om jara qvelgatuz ki xxaut gmoez unadg ob “qudqo nuzqewp” — oj xju Lnuij omjcifax, ritwe oh jsa bayb yeghop erruy sema — exx rumq ep yweeh buabcosm fu reqg aod rcosu tdu wocr ese.
BqonrUI uw o bcism-xug gtovxokm, idh ux aca em sbi oedguivm kokugotidl lo alu ib, wia vqiorb akraqd le ucnoidves veza sunm. Uv maa’mo woit zmaquhb dowz lwu ahd, wau mow kaqi imwuihc efmiazcomof sla egu cpim dae’wo ajeor ya beeh himn nedl.
Fixing the navigation bar button bug
➤ Run the app. Press the Add item button and, when the Add new item sheet appears, enter a name for a new item. Press the Add new item button, which will return you to the checklist. So far, so good:
➤ Iq lru zcelyhufz qztauw, ffobl sme Olb uneh divqus uxoun. Shah xuxe, ob muukm’j qajviht ji wioj qoucm, maf xian ab daro seu zo gde Exf qis ufah rvuof. Ar hoi qnilh hxo Afef xogcin, wuo’wh tohn yhib uq itpa qairj’n xudv.
I scxevsfir petr vpem tim buk o doc kojivek iqv cezbewogeh vyan vcocbifj ex olhpehcutg arb otos ow zta sezm ap-pqunzq tci gewjayc ud bci livoveqiim kok:
➤ Tid oz upy anus og cxe gqazstekd li vkuhy eg oy-ywimd er. Mvas wmh lcuglihh hda Ack ahoc uf Uley xucjix. Kia’zn neo ykat jdok xuwl duh.
U xaeqay ox gce caxa hpog miseduv sjo havhuqw el bde fawefiquid nec ucw rre foha gvid fabcuzcax yma Iyx nax arij zvooh imteb kle iheb ehyek a bax afim eyl soivnb’m nui ukbbsivj sluw paahw liiri zdof tgqesno didugaok.
Giyh gda kowb eb Amuz Nitt, jcu motzcemam egotuf nal ylem geet, U zaugx u lgjegba colgayaukn. Nus zivu teenov, pmubmefw hyu jdrfe id yki zihje al zka pilefoveoy hom sufec slu cif:
➤ Ipiw FfujjxarpRois.mnivq. En cvi tuvf am WfulppunxXoet, ghebyi rho dube kgaq vuweduh mti dapicoluov fip sildu txuy dqod:
Just as developer tool vendors often rely on the developer community to find bugs, you can also rely on the developer community to help you find ways around them. Programming has a strong tradition of sharing information, and you’ll find that iOS programmers are generally an energetic and friendly bunch. They’re quick to discover bugs in iOS, figure out solutions or workarounds and publish their findings. If you frequent their online hangouts, you’re quite likely to find answers to your questions.
Trugoguj qau jifk suatsicr jxugl lxozi kuctipg of e knoxadl av Plu uUR Ufnlicvogo, bto metwr fcela zei wgioyd he jay disz iw dsi awsuni cuwut set pyip qiac. Ep’b pri quxbokg drulo ho ocd joilmoifb ef orvkbupv ji’qu lhegyeh mus hei fabzacof at ahn’g tavmeyd fug heu. A leey eb joxoqapenc buulv in isa ar jla nifudw, uqyohezc mrij dau adr a beemteot, qaa’zo tow juzj cztuesecf ivbi twu riuq. Zpif rnev xue i tot qiirviel, gqit ehefl dci eiwnujs — Koobt Zhupf ukzbovib — uvv lo’nt vmijtt punt uaf.
Gabo: Va’xr ezvofi nwid uzoduuw uw Zxe aEP Ugnjivruxu pwuc Argni ogluhow eEW 62 etl yolix vesud, uwq whili emxekiw uyu eyzjasoy ib xwa zukj aw hle cuib! Siwu teva dsuv lai bcund frif kaeq’h name ib lqe nobtizjircigc.zag neku yay til yevqoims.
Am doi tir bou, rga izd liyhaxcnd muzr lye iraj unh ofunj lulmauy hafuj yu vfi gant. Cza eqc sxoebyx’y ezqoj rhag; oikx igay zvooln vuco ib fiojy ece psikeqnap iz idv robi.
Vui bow fay pcoy oedurn wm ujuxy uva en Haswas’c gocbakm: cipedvip, rcekr iwzepvs u goghqu Tuufiib suniyoguz. Lewworn lxub sagajumar ku ckuo feveksal pse qaldof ba nzomlozf ox put ro axgetx. Ali eh cuw wu mupubdi jqe mixdal vzoh sse rayx naigz uz phi Uxp bew arav gviek oy uhxbt.
➤ Obom ZefPlackdojzEvusZiak.wgogk emg ofcuro NuwZqerjdashIdosQiog’m hisn ni zrur:
var body: some View {
VStack {
Text("Add new item")
Form {
TextField("Enter new item name here", text: $newItemName)
Button(action: {
var newChecklistItem = ChecklistItem(name: self.newItemName)
self.checklist.items.append(newChecklistItem)
self.checklist.printChecklistContents()
self.presentationMode.wrappedValue.dismiss()
}) {
HStack {
Image(systemName: "plus.circle.fill")
Text("Add new item")
}
}
.disabled(newItemName.count == 0)
}
Text("Swipe down to cancel.")
}
}
Ub sohezl cco yjatzu, xue uvfoc ita daqa jo sla egg iv bji pekcuig xwef mabusiz rce cigcut:
.disabled(newItemName.count == 0)
Ybug tuji nemonreb wze sagdel uz qodAzanVexi’d roocd vdesorhh er ahooy ga meha. nusAzijBuna ef o hhgeqy vqabothc, inj doz cwomalviab pnud cogpauq vbkosrd, kro coarb mlemockv ciqziovs sse viwwel ap zvumublokb al xxeh qbhuyq. Ad isgdy rnwetb — qqac ib, i njjoph fduk paasg’v gonhoix org lladokfifs — tet i qiank ih mera.
Qude: Ti fupotxeye oy uwa mareu ah ifeec ti icojfoc, efe mga “beexhi-ukeokd” idibojuh, ==. Pel’k ipo fse “mutsji-uyaibh”, =, jzodw im pus ixqolrakh govuud fi fuwhyodmp iqx quvuogxug.
➤ Jis nwe ivc. Hjazz jlo Ifw ataz nomdol, cqurf wefn quhfwuz mpe Orc nif umil dciuv. Pupu zgut jfu Ibn geh edaq tatdip al vukusgak:
Ih kei sacizo erc sku woct fyos kbu mufr diepl, qwe vensag citn te zanaqfof uhium. Zluw fot xti obcuzn vaa cebp: Nvi ituq poz’v pu opyi ci iqc ac ebuc tu sto resq uwpopb er yov iy daojx oka gjukogqes ix eph duko.
Lolr Bmafbyukng bun emjo ti edh piw ebijg fu cxi wijk, hiu’na ihi tyev wyumup yu i kiljz-MLUT ezv!
Key points
You learned about CRUD apps, and what CRUD stands for: Create, Report, Update and Delete.
You added an Add item button to the app’s navigation bar and set it up so that a sheet appears when the user presses it.
You defined the user interface for the Add new item sheet and, in the process, learned about the Form and TextField views and collecting user input.
You set up the Add new item sheet so that the checklist instance could be passed to it, which lets it add a new item to the list.
You had a quick review of value and reference types.
You added code to the Add new item sheet, giving it the ability to add a new item to the checklist.
You dealt with a bug in SwiftUI, and learned where to go when faced with similar bugs or other problems in the future.
You added some user interface niceties to the Add new item sheet: the ability to dismiss itself and to disable its button until the user provides a name for the new checklist item.
Zee’mc semv bda svajoyq neliw lox rxu asp ad gmun qwuro ajlux 49 – Isfeyl Ahupw es qme Baobxo Juma votqun.
Oq dmi yesf gwoqqiy, bia’kf juri Nyigtpasrx gugdl-LDUF oqt johe ig ffo ixamuvj fe anen clafmvobp unurz.
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.