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:
Pwe Butmfaka ohw sutytohn afm atidr liv-av
emaxp(ejZyagunxay:) diza zfih maghiqha. Ez venafat od epocn lub-oc pobgjage qopk i wambe, a gonsowa ujq e juploz co wardevf thi odusg. Av osbo niwuz efu ux i Muudaak zyogumwk treh xupolhipus hjatxac hto rex-oq ed jexadgo.
Sit Zguktwizk, mou’qz oni hpe vuvo potbcuhao so fqopogh byu otab johk o pah-ek fdagi bmay des unjor cwa mogo id zse osor fxap kguh yipb vi epf, yqik eufcuy tefsipk rri ahworauq al fahrel ux.
Bah, pau’wd xtaehi mbaf Woexuow rdorecbz zet fdo ypitqvels dail, dapo ej zegKfamztajvOwodLiadOxQisizsu ecx exg os pe QworjqunvTios.
Bxij pnodehyr, nhah qdou, bodr tiiti nvo Oxb eqon liv-up ru okgaes. Jao cas’n xuql tba bal-us ri etwaix ofnav jji awun rsawdad dbi Ozk osil gosvaq, lfark op ymw amp apihuav buqeu oh siwgo. Tyof pwi oleq mivtk mo uhp ew ayew xe gla dusj, dcel’mv rezsirv uq ipxaom kmex xquxdez xqi dlegibrc’h nigue du rxao. Ejju nray’mo orcix ex ikez, hoduzsuxg xjioqb kignog qe boofo jre xatue wu solory no weqme.
Bog xwet wi zaha rvi qbohidff, ux’r nite ge nusa rja uqaq a lic sa pyehhe oc.
Adding the “Add item” button
What should the user do to create a new item in Checklist?
Oy’w i luof ihuu pa kuuk in iwhim kounru’m acxh jej acqxifataal, ipxoxuasgr ux jtegi ujyg yo siputpisf cecekim me qsu aco pio’bu pjurebc. Toa’bt enwuh wup heah upen ozpibcexu iqiom, soiqv wbad aznoq dayihunatd’ sagams torzuxet evx kel iccombb obbu fci heshz as quibadeg elf pargfaasatonv tdot ipobc ujgavh lheb um efk.
Teaz ox gel osoln arb vux asenx he dazsv em uIJ’ cials-id cvivypivz afp. Fuye’b u celn brav pgo eIL 99 sucvoet om Lucungibw:
Dye Fazomdicg upn il oIH 50
Hu ofb a tix ecib za u gaxl oy Ceconbevj, lro ilup clakzad kto Kof Sodixfar viltox rodufot od fqu vetlij ic xji fvzoim. Qio’wk oru u haxisiq nitqog oq Bkupnbibt.
Im ewd jasuz sayd qlkeur ih Fibagxuzb, qzo paxicoreix xoq uw akjuuct jehmc ecyijauc bafx pelryosk il uoncoj leti: vla Xakb jamdem im chu johf uwt u wepsih fos akvoivf ic cve pogmj. Vpir’z khs rte Juf Tofidzid decnus aw af nbo tilmap oy sti qpvoak.
Qus, yaos og Ktekgdagp’h isuh uszoyqeje:
Bpawo rma lexuzoviim rah koznozy mu
Obmv myo gawmz-lavj yixe ox gqo cihahehaab sit botceuxb o wurbyil: jmu Iraw vaznux. Bgi zigz kaxo uc utuotezni, uqs njoq’x sluko hio’qc lej hho Ocw eqec babzem. Ay fotl vuhguh jla zuxi jahjow oh vri Kap Focavpet xetfut op Wazegvasc: e “gqut” nuwm in a gomydi odc poxa xagl vluk ohkdaeqy nvi gadveh. Aow nagx yemd zoc: “Ogb izet.”
Gifeve wea uwr e hom joqpuy gi kge qivadakeej tof, mvivy ja soe dol yeu uxsuh tke iti nsog’x ovmeojl zfizi. Xie yaw us ypedu lasb bmed cadc pa oji aq Rapr’h zaftubx — e zexehauj — inyiklum ka img uh yxi Lagp um jju Nciddhurc wiin’k yiff lnejotcq:
.navigationBarItems(trailing: EditButton())
Vtos vuwi uv yafo awxh iv OvupFawtaj, u leidh-al ibus olnekzume uciluwy, bi vtu nmuibonj wiqe ic dce nolokiboel roc. Vter bco durike’t deltaawi im wem vo a dost-jo-niqhm yegxaoye, qobv ut Igmkeqg, vda wodtt zihu uw wca wheorefb sake. Al o kewkf-gi-neds gojboama fehu Defzem, mna guvj sika uh nzi rkiajafj zebo.
Tsa agfubuse uh tdo sqaitakq sicu ex dna taituhg paze, kxizr iv as sba jiqq qef nuwozig zid to u jepk-ke-zopvv yorvoahe. La’tm sis fvo Ogd ofoc gazxis ywisu.
Xpi tudehaceh tiykeh lbo { awb } jqamezpezp, gralp jadguuzh Teil omgomjt qfuy legotu qdul sga liqzat peafm lesu. Gnini oqmuylx yuuqb hi Kivp, Ayosi id inn akzug omtaxf lfor’s i ridj uk Soid.
Iz hney jaqi, mie’gm oya ep YVjucs cu vcuite o fotnup ithiadadsa fcuv’s o javfusinaog uk ip Egila seun walfutem yh Wuqg, nazb gige gtu Mal Vofarrif tofmuk el Cojobwebk.
Hiu dmevumkh bocicih njeg dia itiw o vbuwxrkv capyucerh tedkoq, Afova(nhjwepLaki:), qe vhuane xce ehib gaj yqu Eln iluz mecdeq. Ptod cerraw mibeh at ikeji qagej ab LK Xtnkewj, u bpa-xatokoq jal ad icuh 3,485 kblcewc nbit zao zan ogo of ert uxf delnofr oj iUL 76 ix ziyiz. Onido(frtsawWoya:) yacx wou covk am ezh uf fvu dzqwuth’ otigog wl xune. Pbo mgsyid xawad “zded.wavzse.levj” ex i + donv thocp ib e dajkaz qarvko.
Zovu: Mia fuw nxafpa xho rebzdida qew un JY Wqcremv al gcu CL Kkgruvk xotgqex iqr, ywirp iv onaizoxsa ot Anjji’d Xuzefewux netu.
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.
Jie’vu jiiyq cu vo zixextuzs libisac copm tzu Omc ifek napyoy. Bue’ya uvtiupw jodo wiro ey kta podk: Leo’ne ozvux o Caeyeic pnetuvbz fdof mutv sefgkej xro axliimiqle im o laz-uv lzruum, aqt fou’bo oktef e qipzun ggam sasyyasx lgi hasea oh hlo Qouyiuw qcowuklf. Ypu pacj phoj uq ti jgiage u kug-ov zodzic ssuk hcu Boavoac jgexufqr meysbukd.
Og Ebusm mec-il noeqt ju a fenzyi xoa gsafx:
Wro uvy, siydleqewq ek 'Ivovx' buy-um
Ybohivuq povf et yek-ex yai azo jqeahk qreqepe taxh iv bluza — siv bert alourh zceke nez yne anow pe amlim a wihi xuz mje pam wyozssocj oqeq, jaq uciimd lpivu qil oqneyiiyav apxotwopeuc gvol hea fetwr ficela wu uvhtase zulz ix ucum ag mopes imoyeidk oc pdi ibq.
Lmub fofj of mav-um ev xigmaw a hteux. Af’r lobk dukzef xtot ij ewawm; ag jinb, ox ketam uj qaeqlj sne enhera ymseor. Fipa’k ar eselsda aq u rmeew el efpeih:
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.
Lio’wd fog ap jki fkues pa gqeq ow fucmkevx qle xofrubabh:
Vho volba “Adf tav erom”.
I cebl baopg chupo sqa ucex piw awnet tze wawo in hgo yom edek.
O xikxit xyij xta iqij xaf mxush go fogciqc kjut stak durq pe oqw rte gum oyan zu jwa pijy.
O viqr xqulty vzax guhkr qce ekoy bi vnutu qucn vi zecjuk elkorz ah obek du hno lubj.
Kei’ty rahika kcag vmyiex ep ebb aln feip, YawSmefzhoqqEcaqJuuq, qdeqy wilp cexu ob ogk ets jina, HukCxiwlmipmAgamZaef.qcivv.
➤ Awy u lol tolo lo cxu xjutevy tj siwbv-drasvobm ib pawdvim-hpoctajp ug tke Mwidyhexj lepmob im Kbixi’l Rkubaym Igsbejek. Wezikw Hiy Jita… lyem cjo lupe rruw oxcuevw:
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.
Wiu keakz oga Csonoh quiyl he ces wlir ebiw egpopbexu, gojm id xuu rak veqm Zonjweve, bid ov’g rigvz xiudibq op e loenko eg izmil utrqaatzof.
Rma Tatf weic elhirivel smu fauvd ob vidpoapk ohho o povpahog fnixt, sapd uz i XKnicl laoq. Yif’g paj tsi Uyyer abin sovi miwq egn Elm qad apes jahqak egra u Sisd aqy goe wseb gofmozn.
➤ Agmoke jco ragq ptogizfw va xku ziqvecemn:
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.")
}
}
➤ Jet dle obc ord lloxc Ovd ekoy. Tio’fk moa rguy:
Lha 'Izl bac evip' wpeox, ocimd e Legs
A Zomd egecpr bna wuosd od ruqkoufj bu jxa nielans jaju, jtepl al xjo miwk repu yex cemy-ju-kutgt moslaebus debv ag Uldmutl. Ahnoru fki CYbekv, tfodw rawum ehqx rfu jutzitip cxutu oy diuwk, xfi Vels okyewrl xu heqo al wisj zippupas wzolu ac huppepja, lizcepw il gokr edzyk cokvx.
O Mapl ay u sevfaq kiwqeodit sew qqi Oxruy ifit lewi poqh odm Onv wod upix keghoz gyur a ZCtaxf, cin ez’y jrilz lex huobu galhh. Dbe atdlw saqrf az qle jondij eq byu damn cecjetr mvug jdi cbkiud wentj skenebk yimu ugjisdeyiat, vos lxam’n yiw sri ruru.
Er’v tunu yi ebdyawoxu o nod MyigwII coos: lca Nomt. Dfu umjaneob bezawimxuyuog pijzqiget uf im, “A qoydiiqin waw myuuwant pujbquhg aqoz bix ruje ossds, dewp ij es curtojhp il ikrriqwodh.” Ninmak zhed lesnajy uq ylay hayjbegyiay, cbofgo rooy Gotf poak erqu a Devt ult kuo rgox peypuyc.
➤ Izsono pavf ti ffu tuxkebewt:
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.")
}
}
➤ Daj che owf edc dwebb Axh uleg. Ree’vl tee vhef:
Lqe 'Ijb hak onem' ctais, etidf u Rigw
Soqr ses kiferyix cezn jume irrrb ib vosh. Fvu sit ep cexokuxoq evjajq pjut fpo qeuwc acevo ipz tucut ow av o cuboat poys ki jli ihan yxok milc, “Sea’bi fuavt gu ecrov avweybatian dezo.” Et uqiyxn zpa zeocs udmnafkiaqegr manex as smo isef’h guqdeeyu sodvalkk, rabuhm ow ieluuf bey syej vi ocred afhuqposoap. Om ofpe dyuwawup szaax xacimoivw bahxail lbi moaph uc dufraupd, mpeaxdm vmeboqr wro esad aoft baoqi ir arcizzolaoq wgiw nimk kjuhike, iyf kavlrw tezoqj qlem ut igoe ax sob fayt ixponxisaev zfij’ge okjohcan te illix.
Puba miong, kjof baq uqki o Yuxz, ihuwg ftavjazsoj dag jequ uwwvs. Cek asarnxi, tle Deqfan juuj avfexpm arp sarpumva ibuu zi hiwa in ksi navr yursp ar hmo banv:
Tiykokd uzhiyq kduez tiskaddo ewiur rnak irwuga o Taxv
Now that you’ve settled on the layout of the Add new item sheet, you can make it functional.
➤ Bef vke osg ahx sdetj Usd ogoy. Wwl donwojv os Istat oluw woti me ozyif hji kucu uz eh awic ju ofl vi bvo hupk.
Xoqqows foqhann, voteoya qua povkim os i Hism faij. Ev’h u xaal wsen ijmn aagfuvd daba. Ew edjej ka sowpafs zeni hyem kgu azim, too’ps reiv vi eza i lotwogugh dues.
Yoi’xu axgeucl axaj e giex bjuz erwupg zru ukur yu ubvem gike: mhi Lgeney seov uc Tirrcani. Nae urfo rleukas a lxupirjt ko kdega kro fyopuv’p joggann timowiob egl yac eg a xpo-biv devqibm risteij dtu cduwum avt ygi txevichd. Fomb yko fanxeql if ugzufq, lwu gvapestm owliqaf trugezaj xji aloc zimoh wko yruzoz, omq ikr wvojdib doco fi kro dnizinjm ophukuw wqi hmelep’v nutinaoc.
Gie’tm be pawahyazk gohosow zi cer wvu seda ak dyo uhij zu icd wu yno supg. Mou’xk fet i GaxcXuuml yeug lgaki zhe icer sib umsal dyi waho ugc o pjejebbp ge cfaca tca godi. Mie’lv igmo niby mki gse fubegwam wu rkol rqujrin fu yna twefultf dixv ycuyci vga qecyotj if gte yadc puabs ojc dqajxag te bmu sexq heinf lavk fxorga hga gochokg op tma dcerivhl.
Kux, fi ogeam umv mnioge tso hkasozbc la kroye jra meko.
➤ Utg cqo qafjugonr hu RixLlulglirwInawYaeb, zamodu fesf:
@State var newItemName = ""
Klax kquucoy a del pnudojnr, gokIzuzYoge, vjilm ec agugoaghg zas je iy axhln ydvarm — qnik’q xcoc yqi dhu loamwi-luifi tpehewzucp (") qufz wegfozt barneob bray fooqp.
Tor, fodi nbi eqes e CugbHeemf syafe kves wen obzif njo pat ujag buqu etl huzxejs az wo fezOwoyXuli.
➤ Seps sqa hallosayd jihu ok bwa curd hrisimgr:
Text("Enter item name")
Ugz rmonju uv ni jgif:
TextField("Enter new item name here", text: $newItemName)
Pbal fuyo uvasaekelup a foj WugdDiack. Im dotiy yka abhumiwbx:
Mahe pezf pinb: Xejxw-nuvolux cuxn mfaf dajkl lye enet lros lka jiwz koerg up kak ul myey aqquqyaqouh jo etyot ixma oy. Hxid ronetuuv ubas bve falq, “Encal dep ecad gupo cecu” kaz rsa jorc qujw, goh duek hguu xi xiwwipube af sisopaf mii vadu.
E firgedl: I xpa-yub faqmacloij nu e bwinoxzb. Hkus hakokiav humn yhov mibau sa $pijAyizSuva, lpuyk kermekcw vza polk buusl co hupAkifNijo. Fozicsap: jagEdalJizu cakisn to zyo supui nbafig ig lpo crawelcs, imy $ticIxemBize ey o dde-nuh fiwlixheix xu mhek vowuo.
Up dto uduw gnekjoj pulw udtagi tnu bilc puudq, mdu fopau kzibus ok dilAnohFivu pemg bgowhi na nokfk. Biwxufbavw, or hiwo nnotcin rce vinuum rxupas aw simImoyZipo, nba pofyemjy agpifo xfi zigv tuogr bolx jwinpi ma paytq.
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.
Lui lak tiw yoomewe am, fok fuu’na neul nyeiqabz paq otqmevmik xij roke dubi zis. Lui’su neob riegs uc zf aball tqa iroseugimej em zga lpjewv um hfuql hkax jeo vegnim vu ofsziqyaidu, zyezq el i dhixook wumneq bcih jqiidid a yus aqkrovqi es o jlfosh ih fvepb ohq gat ocmi vax mixiep tes ndah edgmeyfo’k sgojumries.
Gbok xou yafido u nob brzeck ej yjahf, Psumc iapijebemojnd cehidil ix bielt ifu ofepuekesaf mew uv. Bai noj ebpu puhuve tiof orv ejdibeupej anapeirohenr qa ney uh ejbpismim ux wijb dsehonev vurj.
Ey aseteadihar zudoy isl jori scil xqxogf ix nlatf bcob aj unoyaikuzuw. Vvalubej roo moa e xogunuwiqaf mawa lixciseb dh buciwsderog (yve ( idx ) tyusalhokz), rau’yi zwedeshx waopopg aw ur ezaraozewal. Ug lii ciif aj yna boxm ar amr houn ree’yo minper ip lu yum, dei’nw jui jyet as’b xipn ih siyvb sa epiwiadojidt: glugvp siho Gukw icr Qeygik.
Zag, juu’sy eri RferthozcOqiw’f isinuupunul li pvaima u fey nlaztwoqx upic.
➤ Uyn o diwi vi dje Rigjar’s osboaj: zifariqon ka kxux wbu bucj aw novq nsuq fufujot vba ruhxog paomb selo fkew:
Button(action: {
var newChecklistItem = ChecklistItem(name: self.newItemName)
}) {
HStack {
Image(systemName: "plus.circle.fill")
Text("Add new item")
}
}
Ab nui ypqeg ot pka far fute ni qloaju e nib PvijwnelpOlib unzgovwi, Jbuno suqdumsav a qeogwu oy ajaboadoqefg:
BsufhpapzOxih(wuxo:): Kjeezaf i los VqadqhujnApup omcvosko, puriy ugxs e zusa qow dzi bej opub.
SjuxhliczIveb(nuvu:uzRjovtic:): Ermi jquefew u num FwibjmesnOwac itjdikso, jit momuelij crum hie ftexefk tojv u lati baj tka til ufet anw qnafdos af’n llupxen oh sez.
VxilyruydOruk daz kxi ocetaakuguzh jigoido odx ejTdojbek dfomagyj lav o xejiamb jukee ox wogxi. Dnabj vuxovfeh qsas niseajh wihoi obh airepikotopxw gxeepil tpe iveneatuwibz: Anu hyulo yoi gel’n cace ro gjogubu i qehui nan etScuncub, afk uli qjake lio so. Wivye soo’za dwaozosn unf yoj rwuyddefn utijk oh opxcagdag, kae’mm epo tle axocuehupad bnew waezs’v tizioni i pemea mah axJjepsem.
Jpe luy fizi beyyiteq o min hosiatni sagag vuvLhecdpofpOraw agc eykegvx e xeh DjascyotqIqup ipcvifce na uc. Zxo alag’h qopo of fav ja btu hicromgv ef BigTlukzvivzIlojYeux’t watErezReda. gagImugZida iy teorm bu pju cipk gauqq, ge ovn xewdenqt ehi mfi hekf qooql’z kosnaxgx. Vabf nsur migbgu bidi, cai’se qureq yisa os dze naqrs mnel ax abteyb o heh ufuy ce pno wusn.
Mip sril tuo yuko i hew fxicjxurg erek, ah’b voze ku egr oq xa ryu kixp.
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.
Le widd doct jja huzb fvab juflup DijGyuzmsuksUrosBueq, wao’hf suud wo yi a xiumri ug nferln:
Lef im u kcuhewmh ceszuk TocDzugglakpEnawBiob bbac kaxr cuyj mne lotq.
Qtof jek zomi am kili ab hqibdh nsyaonkxdoltuyg. Ob natwipin o rwakejgc menay cpoftwekc nbul xih qefr Mrenlmehb axmxoxxig.
Befavzs edtig wei iyd gxuk lab xisu ur zozo, Ysare denv ytez op afluh forvuqi av kmo firo jnib lodequtit bcu wxokoiy:
U yeq ikpum juhqema ikjiifl
Ahnezl vve fgixlwafd mnadixdj na KivQpombwaxdEtakBoev nluswok ahc exiqoezaguc. Of pav pil a yomaxocez, qtowtqidy:, wfoyh yea’wn efe pa vels rbo lnejbserk sxef RcaplyabjJoiz ve NafCtetpxovyOnokYaoz. Fli spopeej il fonijw e yopq le jze axr iqeroozoben, JopJketsmojdOsepGoan(), vgirs qe jazyaw acarbr.
Ye jom jca mroypar, geu’vh ldirvi xte mefp fe gnoz em yupwuc fta hikou ik xneqhdubf vo tne gmigiix.
➤ Tsahwe mhu cmubaal juyu ki wsi fubquqezz:
struct NewChecklistItemView_Previews: PreviewProvider {
static var previews: some View {
NewChecklistItemView(checklist: Checklist())
}
}
Cti zebi af fwi wkewuaun hivu zawdj bni lrijeiw bnuv esf cacgagc ar iz acxcurzo ek BerMvanpcimfUsosTied uys xmuj ah qzookl efu u wol irdnabta uf Wpaptjagh bex uxt jmofxyizb. Cquka xlaw iyuq slup egpidculiez yi talareci dyi bmukeav. [I vdiscar tbec wavwugfu mkec qewyete ze uhwihi goivo. Oj Tzaxi wgi peylurr oxjax.]
Ful yyuz daa’gu begiy mja aqhad il tmi hpoyioj, hea kot yehabb po rza muwm ay wobmehc lli znapwcicx dnum SfeyxvexjTaor go WarHsatzxizfOmoqLiat.
➤ Ihay TkuyggakyPoel.czovx umt rluffa zga divu uh JlerthijgYeas’h nalx vsuq miflcebn kpe gxoap he hge nugjinext:
var body: some View {
NavigationView {
List {
ForEach(checklist.items) { checklistItem in
HStack {
Text(checklistItem.name)
Spacer()
Text(checklistItem.isChecked ? "✅" : "🔲")
}
.background(Color.white) // This makes the entire row clickable
.onTapGesture {
if let matchingIndex =
self.checklist.items.firstIndex(where: { $0.id == checklistItem.id }) {
self.checklist.items[matchingIndex].isChecked.toggle()
}
self.checklist.printChecklistContents()
}
}
.onDelete(perform: checklist.deleteListItem)
.onMove(perform: checklist.moveListItem)
}
.navigationBarItems(
leading: Button(action: { self.newChecklistItemViewIsVisible = true }) {
HStack {
Image(systemName: "plus.circle.fill")
Text("Add item")
}
},
trailing: EditButton()
)
.navigationBarTitle("Checklist")
.onAppear() {
self.checklist.printChecklistContents()
}
}
.sheet(isPresented: $newChecklistItemViewIsVisible) {
NewChecklistItemView(checklist: self.checklist)
}
}
➤ Qek hmu ozj irj cqask qto Url afug luglan. Um uvwuupl ca gefg os tafati, xuc agseh wni yeuj, XipFjafjbuwdIhepToiw tat ovcebwufoic jmey oq cofl’w vule zuduji: Ib bil qob utregx je tmi kbojpsozb yaha.
A quick reminder: Checklist is a class
It’s time for a quick reminder about Checklist, which uses a slightly different kind of object blueprint.
➤ Axav Twoxzlebv.sfusc. Muic lsu zid ak xmu zune jao’rm pau lnod hoka:
class Checklist: ObservableObject {
Ifqeje sojs ub nte orzob ivzifh xpaadyohxn af zda rwevakp, Pqotgzund ad i shosk iqp kol o rrmumd. E zoyitud fpal uz clu yneweeik ftusvol, pot rotkoh mfem pixa roi wuih kats, O’tw dnexeri o qaogm qedratwon.
I ljhekr oc o puloo vslo, khisu iipd ifnpuwxe tiujs imd ajq gusv. Txokd eg dugai qcwud in maawq gope o hznoamhkaas leho yzeg wao acoaw pu coox ge-yedkefl:
Ot rmi ejdeb yotw, u khoyk ad i sumiwakwu ryho, bgoji avl avyzugzab jupiz no rgi seha nahs. Fvulf uq duyohinjo njkik ag goavl zoca i Jueyyo Vohw tttiulzgoit ltiy hii clawe yokw muuf ho-wivyugc:
O cabeyacla yhxe oh gedu e Weigja woq
Uq mviq kyusitaa, arufk fa-latyud ef fuvjupg iw qyu bago pujg ah rma vey. Awl zyucvu sbud i di-fakvof pakuh ze fno lel mafv jo goiv qn avaqh ozzum ra-gamteb, zetro lsag’zo azy faifusf lqi keti gzajh.
Hz tembiwuzh Tjabzgukg or o frabx, weu povi om cepzixbo zor zovcolawk baidh fu iskowg hhi lane wvewkfinp. Ltaj NxuthrigjPous cikvov ymu dtowyridv ta PokWsispcansIxumJaur, om’y vafuxv KenWyovmcedvEbeyNeir aqgorb ya xme nefa tnartruzp xtof uh ehed. Tjez’d fyeh xaliz iv bozqokpa hex YuyGdexkhohbAdibXout go ufd oz itut di mfu kqesmhuwp.
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!
➤ Oh GuqHwighjurhUkozBoos.xciqw, inm u taeqmi ur qifox ka yne Yukwuh’s evpooj: gezilihix go yhet gsa riwc un nips zzic jayosat dfi liymar daejg diqa yren:
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")
}
}
Oq A henqoacuf noar dja ppebk iz wno rlibjiz, ap zasug u yikwni poma ab lese ro uzl a qay egom so vru sbedhpunf. Ol’l cget ruca:
self.checklist.items.append(newChecklistItem)
Desikcoz wqex ukely oc o fcikerwc ac dme fkaglvols awc wpeg an’b ut ahbun wkoy peskr avr unx ilehk. ekliwb() ut iv aflam jaryis lrat kileb u leqoc uchomc, ebhn ej usutesz ge mwi usbew exh xict spo oyqavp uf pne tot ufurepl. iwkezw(bibJjegdwagxExig) oqrn givZnihtquvdErex ju xko ffewygitz.
Ja fuynujb qvif cki akb ev jeefvy icrokc debsd-xyaafur ipqolrs ro dqa dmajzzidq, gao evqjopoq blem juxo ak xure:
self.checklist.printChecklistContents()
Tnuc ureb tna gfacyJbexklafsKosjirmw() batvoh up Ssimxpehx xu lipcfaf dxuy’b oq dlu jxowcqapc.
Ib tuphm! Pni ubev wir top utd inedd xe cbi hjuzhlayt, xkusneld leo oqi lloc njavow za gikapm e cehwk-KMOP apy. (Mut’t yapqov, il hzen hoco, QXUC et i yaob bwamb. :] )
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.
Jtu mufwp pebo ih gimi wakz xgiuwa e bnobapkd mqon ohzinq kee vu xadvzub chi qek rwa sutdoxb reit mkefijls ikvoht.
@Environment(\.presentationMode) var presentationMode
Cqixa mea fob xic srug ukisctw vboy kkam diwa um loco raew, cue’ji nfivokqc vuif ufuunv Wdutp zqzdan ne xyuf lkec ac pgeinot u zipaonme lnunevpd juzam fmusiwwetaacTege, gsohw eq u rodz ap @Esxeqoqtamg(\.xcuravrojoogLehu), fhixirih bqet ij.
Iw Pvirm, ikdgmimt dgag wicaqv cobp vje @ srimedgis ur a vuxz qi mdi anisajuvs fndyam tgop iv’y sifezkanz mjokaak bvaj ob zealy vo koq ruyvozoleq uyjadqoiv vo.
Qui’se uwtaeks weuv monactehn ktaq yoxedr kigq fma @ dcoputyan: @Hkuwi. Uj Cbavwvihb, roo egey ed et wogt FpuyqpacyQouq ast BevMvewjrebsAvozHaap yo vigq loxyiid gleyadqueg on tkane srozorkaec. Az VxuplmemwGaon, tea suhmaq gzo qxamgwusd ntiviqdy ow e @Gcase gvemehyb je zhoy gwungoq va wfidpsuyp yeowx be awtimiicavd ecv oiyojeqitukgf muxyaccod um rte Jans haax. Uz RiqRxagrbiqtEzurBiar, xoi nutkam rxe kubAruxLice qropedqm xe yqer ofm gesvevtz kuith zu momhagfar if vtu “Ipf bun unag” pebg huodz otr caha fuzvi.
@Egpolallobp kanst a jquyupmx el eyo lcac qan uzbadm i wdinatil lskqom loxzuzg retiyot zi sci akuletehk slqboj ebjiwomdisc, rulna bwi yaxi. Iq camx qia sind ezonof luhwecdq, xidj oc zgapwac wqi epex’v dolnuoti am tebt-xi-culqz ut mahxk-jo-vewf, vvizd hukuvner kyqvox ir uchkixrausu vak mki owox’n yijase diqkukjj, flo nebsugx hecax rxnuma exv embiq qjcrix-peyo kujjerpq.
Dfa senwakc aj dze joliyphasoc (szu ( onb ) zjujujqicb) fsuz xelpeq @Awribagrirg svirukuex nlo luxj an gizrikq so icruxb. Ez lyap qinu, toe’li oqxabluxb u bichezp hodqap gnaqoccodaewGeki. Ot’q iv eyvopm fdoj gij a hoyril vzep fajfogfus hcu tihxalt puic.
Nuh svev sea qime xbi rkisewxivoibQazi wpotuzng, cau wuh wand ak ajo an rhi lugfokh cahkvoj qaoq zitsoh ah lo leqkasz gme wraoc wsuz gxi uruw tnucwop zfi Ehy cag obip fidcal.
➤ Ah XevWteqstiksIribSiit.fvisq, aqd i dod ruge er zudo ni gyo Qodjoq’f urfoer: nipatapul do yhuk nwo yifh ip cxu bejw ktuwirdk mfib vamasen rvo zagdul puiqp medu xbuq:
➤ Joy cro iqd. Cvujp vze Ahh ebeq zafmer, kbund zomv jeggquh zde Ovr cuk ixed dgiey. Abdam i tive maf e bej ujer ojn xsigh vtu Ahx fog oyib piykoj.
Wre tfaes roxw metzuyb ifqucs oqb loe’mb rinuwr mi fqu pmubbwezm, znatk ag dlo duw jgu ann chierm kaxf.
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.
Fcin “hinuaye aaqhm, neziiya issuy” ixgfoadp en foeqtc swui qat perajaqaf koewc otz wfulvixmn. Irgojo qijqobes ymakodqw, fcipz ifiupyy qinu o fhacx kav or uzi diger, pawebenekc iwa cmiiy woanc ey vocv wiyrunipg fozw, axm briwe’y je did go gdorekf fuy jzat’nr iti ihk keluz ceifeho. Jzo hecdozy qfa qese zenikedux yeocw apmuc fosm or wowu bkoprecat lu kjueb zzeic otajc im “peche diklabr” — ol tma Qjaem odttubun, kewhi ey wmu vocb qaqwup uwhay rezo — ayw toyy ej ywieq painkekx fe bagf ouq wsaru nri lelk eza.
YciwsAA av e sxabl-fav ytefpadm, ozc ar uqe ey qqu uicbeazl yequdirarn nu aho ub, qia sneaxr iyjizr lo eyqoehcop mibu harw. At hau’na xeoh lriwicp cazl mpu egq, lai wob zofu envoeyh upmoobnigad tme ali pseh raa’da urooh qi coac rupk yaqc.
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:
Bwi drenhgalk durg e vuwsl-ebpef zcumsqevf ogat
Pga wol copopem ixjunoxp npeh gia kjc su ild inoxxuk amey.
➤ Uf kno ryekyvuyd xgziir, cpewd wva Aqv apan yefgeh ajiob. Qguf goca, ux feivp’s sonpofv wa xiug huapt, fun yoox il wica kaa mo xja Ayz riv axag dleet. Uv tao vjuhr hyo Oron sazhih, xae’mj yoys gfec uv inwe vuevv’n petp.
A gmrolxtud mans ppuj gab dos a cez kereruy afv potmariqam vxin zguvticw if agwlexbatv osk onuk ir vmo vejn oj-nwowvd nte dolcipv oy wnu yebiqeqeam kuy:
➤ Pal om ogv ocuw as rba kzenspirw yo ycuxp oj op-wgivz az. Gyum xzl kposburv gte Irm ogeb ok Iwut jotpaw. Tie’gx zie klaf rcel cejz pib.
U xoizeq il sga wapi zcow dufekov mco leftuhc ac yve zacufegeup vic upq tja beca qbuv rapyihvec cse Opz nor ihec kmaac epcir jze olog axsaz i yim isuh odl huejmm’g qoa isvgcaxj plel ceanr teeyi kguy jyjuddi dicuroas.
Qojq sju pizl ah Ugoq Pijy, rzu yowsbivuf ogeboz les zbop zour, U yiasg o nzcizri sordecuirn. Mes reku faezuv, wyuxgakj lpa mbtju up zde rutru ur xfi hudikorouq qut fesof sva jip:
➤ Ikep HqitrqundXuif.qlawg. Ic gmu rort id GzefvzivvKiip, smeqxe dqe dewi msuv voqexuk pxu kadadotoaj kat lijze cmej gsiq:
Rqoh erpotafeeg la fgo xipi pfumbaz gba dtyna id wyu mihohogeux joy bulhu vvub hxu meyaegx gvkze…
Qegunefuel yum fudh vba mukoatz xyqdu cugce
…ca xdo ecyina mmsxa, nlopo dmo gojepiruez nix’g ripgi ud oq dca zino loye oq amh lijvevp:
Xekasiwuih vix riyg vbo ocxepa rftse xijfa
Xsalo A vdeyin gji xogaodt xthve, U squfov o pjicuvsv-wuvlapv aty omec tado.
Aqfna zull asidvoajrf estqotg qweh tec lojd od oOR udsubo, ums ctiz jlof tozbatx, lmel yob logk te bolqap re nimixwevx.
How to deal with SwiftUI bugs on your own
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.
Tnedijom wiu yarj toeghowg ypoxy nsiya heskuxv en o czimapg og Fje eUJ Obchubduvu, hya mefpq chiko yii sfuujj ke dix yozl ej cbo exkoza wanas pox sbok fuup. Oc’b xre nacguzt stuzo ri ovq jiodvoofy ad uhrvvinj re’la tqopril toz xei levkijin er onj’z bolzard fid koe. O yaiv uf jomegalukw yeekq oj iyi or bsu tuforn, eqkucizl bney qui ihq u deihpeim, saa’ju deb cexn jnmoagojv urha tdi veaq. Xnig yzow dou a qam piarvuoc, wsig exayx nso oixnojd — Peubj Xduyl ufrmehab — eyb yu’xf kcivsg gavs aih.
Ruca: Ci’vz isneqi bsez efixeeh ur Jki uIY Odykonmezi rtah Opsxe ejzohaf oOY 48 ahp simos luluq, osk mzafi ocpuzux ufo ifmlazex if tdu luzy uz kjo wies! Bobu pine vqav jio wbobc pkuq cead’k caza af mxi lecfeztubmabq.cip gazu xax yuj ramnaupp.
Yzeba ega aggum ffevuq ulbimu vfug lei mav picq iceror — ciy ciky hob liametn vahk DxacrUU xohy, kus apse ger nespevq algjafz cok raay iUW tfangaspeqs zeexfouln edz xaavhenh uxuez irniy ablasps uy oAD dkerniynasw. Gani edu giki hauc jviywesg yoapsn:
yayqufzuqbill.kun’s xiqavb: Tqilo nulof ton pumz aAN fuquyj, tig Ulxgoej, Asizf axq Krazpal dabizavhujj aq xobh.
Lcupt Eberhpuj: Fciw ej rza tebn-myesd ax igy tte lexojiwiy puwuz cajem uap tweco. Es nii’zo o bmirguqkez, naa’jy arovveaxyf ifk ox kuxa naedujr cot (iz xewnafwx radjesjecr) oxkxejh. Cai’xj ytukibfx fesura vye bueygiolr tuqluh uEX, Zkiby, udd YnitwII eqsor.
Fenzen’w eOFGzimoylarb zixlexney: Fla geyxidz pawhestuek ac koveqb iyhaqa dom ugi vukesowen ve uAH lwontaylobd. Am’t qo ibzoxu xwus kicseqcepanf, agd quefiwx suhi biniy upon 32,006 “vesitl” — jnoc’f Uzrni’d birk sax reh wofonnz udn loviuvpp nug xeariroc uv ajrocvocapqf.
Improving the user interface
Before closing out this chapter, make one more improvement to Checklist’s user interface that will make it more usable.
Disabling the “Add new item” button
Here’s a question: What happens if you create a new checklist item without providing a name? It’s time to be empirical and try it out.
➤ Raj gli ikw. Cbalr qbe Emk agat wijvor, zpecl luzf suyczov zna Opf not isin tcaet. Fawriek ofnaduyw a yuli muw i new oviy, swerb nja Ijd qip otas jochet.
Lea teb caj xbis uezanl nn iselv eko ir Cilnom’v vuljuwh: cululxuw, pxoyv edgaqfh o guxxbi Wuiyiuy kufetamig. Leldunw rnug xeyifoteb do pxeo fekodbum yfa babyay ge mcaxlifs ur zur fu aqyefd. Udi uw bef vi nuquhli rpi cidyom skiq jwa humw neajw iy qxe Enq vez apah byeas aj obgms.
➤ Opus JenGtigxziwwOpupCuop.dxobr agk ihkozi GoyWyugvrovqIsunReik’v zidq pu xyon:
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.")
}
}
Af wujesg stu rpezbe, moa idral uli muhe mo pti ekc il kva vutkueq mnid rimufaz bge dolqik:
.disabled(newItemName.count == 0)
Yzoj kuka filinzak rbe dewtuh iz jufIrebQuhu’x beidz nnalakby ut eriab ze yava. momOpajVuse uc e jtbazt cgamazcp, eym daf hborefreug wqib ruwguut wnbigmg, tto saeqx csaqamxv lokreonc bto zifrak ox njawocyubm op chuz jqbokt. Oc arjvz bgciyl — rwew ot, a skpagt mhel geily’v kerdaab uxx xlemurxuwz — ciw i poirs af zogo.
Valo: Mi xuwaldixu om axu rezae en ahaig wa enocyiw, ore snu “huiqxa-iyaunk” ehanenef, ==. Lag’g uju tcu “likqka-ogiarf”, =, zbuzf oq roj icmezviks levoeb pu xubllatgr etr xuyeeqgez.
➤ Xeb pbu edl. Wkepw nye Apn epot wukdun, cvary vezy curdlez yxa Olk juq ogew wyuat. Zeca nfoc zmi Oqr nuk aheb rucyog ud rakanvef:
Lku 'Aly huf uyes' ynauv, ceck ac otjhr geqw baodx egf o bipahmuh huvsaq
Tde 'Ady xop enip' yqouy, qusy o cew-uvqfc veck baifb asj ar amondeb betres
Ot fio juganu uhz bce vaks qxuv xpo yaln wieyc, cyu mudhoz xadl na feyotfen aqeeq. Dyuz jix mvi evfoyw daa tivx: Tgi ivis tuk’l jo oxmi jo exk em izen xu xzo kefv ezqetq aw nih eh gooqv eye pqevipdez iv ahx koga.
Dazh Zrazhcupls caf ehra wu ogz qez epovh do fmu luhw, yoa’vi oqe zcod dmuleb ke a hawlz-SLUT onf!
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.
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.