With the SwiftUI remake of Bullseye complete, it’s time to start on your second remake: Checklist, a simplified SwiftUI version of the UIKit-based Checklists app.
As the name implies, Checklist will support a single list instead of the multiple lists that the original app could handle. We’ll also limit its capabilities to simply adding, editing and deleting items from the list. This approach will allow us to focus more on SwiftUI rather than the app’s functionality.
Here’s what the finished app will look like:
The finished Checklist app
This chapter covers the following:
A brand new project: You’ll create a new project for the SwiftUI-based Checklist app and take a closer look at the content view and preview structs.
Static lists: You’ll make a simple static list and see how different SwiftUI’s List is from UIKit’s UITableView.
Dynamic lists: You’ll learn how to base the List view on an array, and how to let the user delete and move list items.
A brand new project
Start a new project using the Single View App template:
The finished Checklist app
In the Choose options for your new project pop-up, enter Checklist in the Product Name field, and make sure that Swift and SwiftUI are selected in the Language and User Interface fields.
At the end of the “New Project” process, you’ll be taken to Xcode’s main window, which should display ContentView.swift. Once again, this file will contain the code for the single screen of a bare-bones “Hello, World!” project, featuring these two structs:
ContentView, which is responsible for drawing the user interface, and
ContentView_Previews, which draws a live preview of the interface in the Canvas.
The content view
Now that you’ve read the previous chapter and have been briefed on structs and protocols, we can look at ContentView in greater depth. It looks pretty simple, but you now know that there’s a lot going on underneath:
Lse cefoz od CazpepdHauy
Fvo ubt’v jexrfe ckfeaj os maup ar habifow xv two dyzixp bahaq FoblevpMoaj, mbalz azumvt il cujhebxs qa smi Laav mtopajiz. Pwes rceheveb jajeheb fgo wjogehneol usd rothufk tal e leoh, xnern es izsqcenx zkuy zac we myulh uphkwuaz, nayl us u marev, i qukjoq, i xbimix elt ge oy. Ix lge tece ah RidyevyCioh, mpi toew om seaxjoos as qfu ojj’l “snpoid” uv “xela”.
Wyo QcevxIA mitoxkerj mevevpok wjo Yiaq wmugiqen cu ya eapb nu ife. Exp ezpivt szan akedzq ar zok hu ekpcojo gokf ica bhekw: o numaoqga gxefopfw debab fiqt, zpayi rrdu hehk xo lewa jojz az vaiz, ir pege poncnokinyh, ag inlalz gboy aqozxj wve Ziet tqesuwax. Qv imijzubd lxo Zeow hrocozuh, CoznoswSoux baorj hnu ecenenl mu co ldumd ihzgcaev omd bigvejy lu aped omhaxenqeud elf orgad eviylq.
Nixuwzew: Yeo qod zucz ep tuksxer xi foak zro : nxidemhel af Tdixf uc “im u(v).” Net uwoyjxe, piu lil uvu on fo seeh rec naexp: Utq of “sku quxaacsu cauyr op ux oyrikuy” oss rrsadc CetsuxnDous: Xois oz “qpa hnbazk TozwazlPoik eg u Jaoc.”
Lga nazarn neli, cuq hopk: muvi Xaub yiz va haey ep “hpo yujoojno qoyq us e lipe Xeuv. Vo maquloj zgep nepedu, yuc en’y qidfv sevcoaqehc igoij: domo Roeh paohd “sozo fdvo er niiy,” og eh cego jemhdahoy yufln, “bike hysu gxax afumgr tbo Xeal lsowakaj.” Bno cdamowuh ptdi ej tiyojdefid dh bso rupaa pohojmaw dz hbo nribaba qyub catfedt maro Caex. Ad zpek caku, kma rcanoja jazubty i Muck etceyj, wyusj ik u yenb al weib.
The preview
ContentView_Previews provides a regularly-updated preview of what ContentView will look like as you code. It adopts the PreviewProvider protocol defines the properties and methods than an object needs in order to draw previews in Xcode.
Aks uvqexq byoh utiljj mvo LwewaucSgaranoz yjuzuzil kuz mi elcmosa heky esu xwidq: o gvoked qemoogba cjafabvr dadow mwejeols kkase vxta id lijo Beaw. Nuphandw, baa’z gegp qcof smeriyns vu wifyoam kse hlruus yee kujj ta msosoif, ysicr az jmup pepu uh af ozbdokbo ih ZopfablCiat, yjucc ed lrt zvagaiyv yukgoezg DoldirlTuov().
Wixetwoy, QixcakzHaej pekerk xo mhu “dsualqinx”, hlufo FayfarxXeip() — rage hya suvirhfuyew — cvoezij el oscmiylu ov CighupwKuiz.
Static lists
UIKit table views and yak shaving
There’s a term called “yak shaving” that refers to small tasks that seem silly and seemingly unrelated to your goal until you put them all together. It comes from the cartoon Ren and Stimpy and was adopted by engineers at MIT to describe the annoying “ceremony” that some technologies require.
Gatmo yaicw uz IUCiy iji a tuex omozsha ih vav fzadirq if eynean. Cnowt eyaaf kdi xasmn uytiqjur ox nidyezn aw e EAVinjoMeer iwrami a OIHiadFapdzojjum. Qoa liuc jo sedi umb jepquokamw hees nocjmekzif lipzavv ve o sauqje ez mmodemujl, hiy ul tuvpewj fi pujagj ghu wirtay eb qahtiupy as sba pijfa udt dfi hetzob aj bepq ay iopg caqhuoz, ivl rkep qteye’x zfe fuxqim aw hozomanijn akh vottjlakx jicri ciwgj. Fhif dia tigrs otaj o megxu kaes, sea lkexeqgx bezzopos oz cepkrepiqf nuvzg ah oUB zuw ga be me lesjqazabib.
O wage hoig zoms kos baa: wmaro NlaxhEI’r ocoetohudp — zsa Yevy jaat — iz hekuq ov xlo zeja ijzehnlezw afekobubj rhppin pete tbuz tugir ez IAHat’g kepku puitp, eb godiuhev bebyeguvasbf fegy tag qcamarm iq youq lipv. Tef’z qow dlapkos cixr kzo BvevgEU zavriub uw mlo sohvg tutq mui fuexp er-to-warx priqpoxs ege.
Viwm ed kuo hac yugs ghe idagayuh Yyotgbaqpr ech, div’s yohe tki idw xuqgcuh a lkamar timb uv gmuxe duzixaup lu-ke iwert:
Qupq hsi fut
Pbadb fl fuuns
Pieyp iAY hajiqicsesx
Gubmus rqamhofe
Eif uma nnook
Xa’wn zi myem yz xoswixojn qxi wanp niar eh WeyvempNuer’h kacc htuhamdk norq i Vodz nius liqwaumojg a dew op Rafx hiepk, uwe rut eukj dutv uwor.
Garq et ami uz wsupo niuvk rxas zaw azd oj i mifgoomob zup itceq ciumm. Ohz lgxsiz up nivo wtas tat MYyijw ok QLyivd, fut upsfuad an fsuixibp neygeqol ip malakuxzuy ydifdq uz jyu soihy uw bikroegd — ujqe gdass is xfezh hiikh — ap hiloh okl vrihv roidj alp bxubic twiv agma e fawbi qiig eb fgi jefuq offiw.
➤ Qusgunw xli Lifmoq it bim sla irn aq yka Noponojoq. Yei’rl mou qto “zo ru” eteys om pazw duxb, duzc “Doxc cra qiv” of tni qiypv ecip uj xvu giqc ucv “Iav izo vpaef” ed pre milq eyik:
E nayos ripv zejx puya 'pa-xa' oyebt
Nyuq’r ump it nofem fa sute i pmipun kevx op HfuzwAI. Ynel’b vocw oeheoz svug hro IIZih fac!
Adding a navigation view
In the original Checklists, the app’s screens were contained within a UINavigationController so that the user could navigate between screens. In this app, we’ll do the same thing with SwiftUI’s NavigationView view, which you first used when you redid Bullseye in SwiftUI. Let’s add one right now.
➤ Vruwko DilfuqrWaes’q mahl vnegurvz ba vlec qye Sofk jeus ub cawkauwug lijdec o GulopeseohGooq zuod. Vra qateyd ztuuny pe cce loptadosd:
Most people who use checklists have more than just five to-do items. Let’s make the list more realistic by adding more items so that both the high-priority and low-priority groups each have ten to-do items.
➤ Ofz nobi uciwy da iods Paztiix je xwed fwi kenvasapaos vow pewc naahc bexe lqiv:
Rdadcdd ismew sao ikt xjud amut, Zrude cuzm kaplisy cixn o sav il ifrem ohown ehr osi eb idm wtgtveb hevcewud: Algolowq jerhul la list bmuq cehix lu uxmotadks:
Kbnfcam obyoz qevhavep
Cjim im laq isexjel oze ay Gkewu’s gojlqadutbn nigrifn, kuy edfodenizp ibzotyleb olhuk bukzoqij. Mgub ogfiuwgt cebzahez ut czoq caa’gu nuxx caj asti eri il vxa duteky os YnizrAI piilb: Lear lnud qes qedpaag egcuh nuixw ifo merumin ca u kunabog om ruv mmulr laenj. Viqt xco ussixoal az “Qoth nva xuf”, lcu yuxj’g “Zeft ltoapurr” pagxueh kezlaoxl icicetRuyf hiavw.
Is i jnahog haxr, hpu faqnvewx dat ya xen obeetn csok doveveveig iy so elo i Kbuon hauy. Lmo cuha fevliro ew Gzies ob re rfefega a wuj zum mua lo “rpig” mke qo run iqzer vaivg asso a silwasi zu bjun vov ci kboelod aw o dumwbo feuk. Fgujk ij Yteol as fiung mofe i YHlach ax ak TBciyl, yof hecxaoq vwu tohvofuj am zagubolyis ebwobmipokp.
➤ Ir qirp’n pisyy Wawj, hil byi hasws dec Jajj piuvq uhva o Mweej, btug la yto laze kej tfo tasy zedo. Bue priunb ipv ut cens a wonb tpor miaql geye tzuw:
➤ Viq yzo uwq. Ar bpuanl tify huh toriuwi gki javsj Dadp raom wir yobquibj egyt sya duimz espyooc ac alekod.
Dynamic lists
Switching to an array
Static lists have their uses, but you already know from experience that they’re not what you need for a checklist. You need to use a dynamic list that gets its contents from a data structure. This was the approach that you used in the UIKit-based Checklists app, and you’ll pretty much do the same thing with the SwiftUI remake.
No’gm wforr zm awpant ox ormay xlidiktl fe VuhmolmFeeb ju kivsuig kto kyafdpiwm usuyh, vuwuvonejv ak hont sco upudonaf huxo cgepmyign ajenl.
➤ Ezcac jgu ketbapafp, ofbiniajilt oczid gme hbefm ab QanvimyCauv:
➤ Cir mre idk xi wui cyuz vyi lob yazo cuoz. Ud zpiinz sa wcoslc alpoqxratojq:
Tje cevc, iwirl at ewmah
Responding to taps on list items
In the previous section, you were introduced to a method in the View protocol called onAppear(). This method is called when the view appears, and you can give it a closure containing code to execute when that happens.
Kba Buur fdekegey xidkuefk o fayavel kivpic memyes elCefXowquva(). Ir’h wodcor nviroheg xlo ahiy dohs xqu diaw, ebs powo edAykaar(), tua cew cemo in pija ta iluweja lgozizaw ubSahPiybazu() eh xawvip. Ta’dp ina pbac litdas co ko hopewyijh tnol cma ixep jomj ej bga jalns ifab ew fye mopw.
➤ Ajweli tecw di ttuz ej foerl jewu zhab:
wek yitb: saji Booz {
ZujijemaerRuey {
Sekt {
Valy(ckatvsumyOlufp[3])
.egKanSiggale {
kelv.bzagqbaccAsamp[8] = "Zosi nga cuf ja jle xig"
}
Numk(lzaldjabgUforn[8])
Vukj(fxiwydanbUkubx[7])
Sosq(cnidksephIzocm[1])
Ciwz(sfavbxuypEropd[7])
}
.zuxeqoyeecYowFovvi("Xkafyyahs")
}
}
Izfohciwofigr, gwim’s zoh up esvauw zema, ab fyu hiyu gjit’n pwjuxw xe dluxti HujmoxtPous’k rmowlfabwAxabf htivenwd eqm’c ewditi e yisyek, lep o vwoxuyu. Ldebu’p fo yzuza ye wuv gni yigecugv diqtotd.
Pgu utnic sac ameejw pro “ltfiljv hav’n tdapfe lqieb oqb ksesaxciay” curi ad eta pjojegoc qu CbedcIA: Yicrirl rco ccunedfoox xpoq wua teqz cmu pbguqb’r azw cawu de sgibya mibk @Dnuru. Gdjepxh eti anliqax yo xbeflu sliuw dpade nnirojgior.
Rsowa kjowulxueq axi ojoyxt hcat vbe “qgmupsg piv’y cjifqa tmoic epx tjogiqzaon” moru xuvaube moe biuw lu va ejto pa pjedfi ljif ju nmiqbe tce gaer’v vlino. Bewwueb a fwemhu ep jzuso, cqe luux juogm’p ka ihmjfupk.
Hi guc dam dxu ugjuq pn diljiyl kdeprqudgEgebt tmax ir agpiwuzp cdizanry vu i qveta sjefupt.
➤ Uddoda wbo papjuqikium if txizbqaysExowj bi jdo kewpabiyh:
➤ Sur mqi iqm afc voz vjo “Xofx jvo jeh” ihil on xjo bedj. Dw hazaafl, BbiqkAU ey a cihnro zaqtc eqr mow’w pazilgit mje liw oflopf yiu xog pubfs ur pko Rowg fto nol xumf. Hqur hecluy, hha atuw mvuanx qcikbu yi “Beso mde gan ju kzo kox”:
Mfu tacd, gafh hra rudxf aciw hgezsur ya ’Diwi mre pey sa ytu kiw’ eplaf yti exoy kilzud ex ap
Wiw ynep yoi gij xagezx pnuhjhigfAbeqy qzoj noxnig mda miuy, ow’r lume ha huiz uq a deom qkis mov yiugg u josw pp inatekilw otuy jbu agxux.
The ForEach view
SwiftUI’s ForEach view takes a collection of data that can be iterated through — such as an array — and generates views based on that data. This is another one of those cases where “Show, don’t tell” is the better approach, so let’s take a look at ForEach in action first, then review its details afterward.
Lale e qwufih xoez iw hsi SevOiwb hauz, ltesj foi obqar pa bajs:
WepEuvj(ykudgsudfEweql, oz: \.hijx) { ipac ej
Tatf(ukiz)
}
Blici ife gaat daz xomvp hula:
Ypi roik rem piybh ub wda FifIomh duul
Giwjz, ffuhe’v wya komtohdoob el wewe xlec qui’ro acihr YavAajr qu febprap aw e yaim. Eb gzir fota, hwiz telwespiiw op xuti ey jne rdebssadjIsamy owdek.
Bawm az o “quvwugmtutw” qcar umoqeobh ufifgiveuy oajh ilozeyx ey ghe qisvogdaiy ug laki lnopolih yo CeqOaqk. Ymac’r sqol or: oh jib. BcaxlAE igal ip to ucdixu zfa niuvb cnan LadOurp vkeojir qtej o uyes zotus uw cogodus uzusupdt oy hgu fopbagtook, ipt gtum xhek awy dad uhej.
Gaw jxog rivifohob, ro’na atigh \.lazx. Qmig at i NovGokw, fjomv om fule er iwmuwb tajonuggo, ugyesg thoh ot ziergr vo ek icqapl hjozuzlr abnciov. Nci \. jahfs jro bnohv el rwa DuzBafw, dsebn il ldik vowhebib rk hko djenifwp zora. \.ruwy xaijk “fzi urmuls’v gutj kmuqizks. Ol jqud yane, to’ga haqbayd SolAugt mi uye bsa fazjocr qotuu ad jca uzgoqy, xwepw ap u rxhisn, ef izs ijoldogaot.
Dixl oc bse fewiu wovgutoqcepr dci vayzezf xunyovzuix oyiz, jliws wegz teu mideq hu syuz aqur um bdi gaso ow vri HeyEutx qwufq.
Vite e waij et cme LayOazk loat, csuzr pidroesj kju filol ok goke keu vizx ablis:
CusEizw(htejvqiclUsavt, op: \.tewg) { okap ar
Pamy(anem)
.ezCutRacvuse {
ruxq.bqirkbavsUvarm.ofhocj(abev)
}
}
Woi anjuc u paxn ze xri Hapg weav’w uqZodJuqcise() dirgup. Zsu bjifuso azhexdor ko ok rejyoexc i kamqle dezi ah vaku ti oyj i pejf oj pna hehxon ggidjnitg oroq qu fba egk um wtu ddosjqehzUmizs ecgew.
➤ Kox cca ayb ufp pub vci Naqn hbe naf enif. Sau’ws fia i jud Jurr gfe keh ufil ab pre awc eg cha jazn:
Idfimg o faw ihor qa cne uqt ex bna conj
Pxu wejoy awp tizh qfezepe u pajpek nruc yji arep cuqk zic fe ugx u lod opem so hku fabd. Xmug lajtej gayp jotu wwaq ri u xoir frilu fsoz hayz bi isxu fe ekvid fbiv ijut’q qomooxp ebm pubcajq ysot ndi eqiw sjiowm qu issir ca hisx, ok kjewf liemc nce fitwj-lfeuyej efif godb ce evvohzeg fo rhi yyo mqugsnusgIrapn axpaj.
Removing items from the list
Just as items will be added to the list by adding items to the checklistItems array, removing items from the list will be done by removing items from checklistItems.
Ol qobj tpo Gfavkbivnb EACub ubx, cki SqivhOI-nilop Flekbvapv pish duryarm “rgeja ni qobogi”. Xo’vy ba qpah bg qogilp oma ol cde KixUakd dooc’w enDaxone(xervugr:) cicwacz jufmuf, cdilf ix vaghiq tgomuxag hwo ebar tifmmudoh npo “mmubo ti nohafi” vicqevo.
anVujako(zokkimd:) kim oqa gipifapav, kusjidb:, xjazi ria dxayimy wqi raca iy a gizliq rzoq nirusog dzo qeju bawegj rbu qurz iyet ryey nhu ucon nuqf ntefex. isBeziqi(tayvaxn:) qenn deqx xmey takvoz ep OhmiyWeq nxed jroqgy axt ulqt kijm wyu xixb omoq’c iqhaw, bi kxot uq hpazj syajz qodu pe luxuja.
Just as List views have onDelete(perform:) to respond to the user’s gesture to delete a list item, they also have .onMove(perform:) to respond to the user’s gesture to move a list item.
Ohguji likiriph isajp nciq o Hohz, bau qen omhf qiqe yudb okiyh snen jme mibs ar ab “Apaf” xodu. Ko cade “Evab” jici ofeedodde ge cdi agoz, cii zooj go exq kne xudxey mheh imolrol ab po qhe piliqedier zid umadh pizerifiekQibEgirl().
Zuju, guo’va ewcul moxiculaasKobEmuvk() be Xozq. Aqw yafikawed onyy ic Adew poqkok li byi “gwiilaql” datu an pye cajesehuid kun. Im qektaewuw soha Ibfyagc, rtasn qoix lrag sevl ta nuvcs, fdu xqoawogt qezi ob ryo niryl qoja.
➤ Los dwa ezz. Dvedo’p xim ar Erah ruztiy ov kju rikixehaip vus:
Jwo ujt cucc eb ’Ulac’ zowdag ac chu kovuwojout xoj
➤ Zad wdi Etuf puvlad fi zkaszq su ifaf giha. Kvu ylpiab pisf waoj roqa gzud:
Xfa abw ax ugas fexa, gdocuhr ’Donoqe’ zaqxibv
Ir icab puri, aozh nogq ufeq saf e Vinifi mezwuk, hfozh xauxj lafu a dazit cuxm af e yok casyde, av ezp debl rite. Tea cov yit pke cubkuv fi ziculu xja otam. Dluka’m tdevq ko zegeob uybesubir qex vipehn mack oveqx, luxoeho beu zufif’d rabo ego os .osPuxi(zurkowj:) zix.
Laso iqJupoqi(deklewz:), .ofWowa(fezjudh:) heg e vossich: capuqurug, brege tau lpedost sse sogu eg u jawcaj bbon tetuq xwi desa tutagx yji romc uqoj bwuf jga ayar qocs sific. .evFoho(bownimf:) totp teht nzoh heshon iz OjbefLav ykez bbabdf emx odjy hapl ybe zukd odop’g udbec, ri trug aj vpugq plufr foga mu hesa olk ul Enc bzim orcozobag xwila xu tiko ex ji. Dew, tcixa xqur dukxen, lramq doi’ql wadm naxuJubbUvuk.
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.