Most apps focus on displaying some type of data to the user. Whether upcoming appointments, past orders or new products, you must clearly show the user the information they come to your app for.
In the previous chapter, you saw a preview of iterating through data when displaying the flights for a day and allowing the user to interact with this data. In this chapter, you’ll dive deeper into the ways SwiftUI provides you to show a list of items to the user of your app.
Iterating through data
Open the starter project for this chapter and go to FlightList.swift in the FlightStatusBoard group. You’ll see a slightly different view than the one you created in the previous chapter. In place of List, which you’ll work with later in this chapter, you’ll start by examining ForEach.
SwiftUI uses ForEach as a fundamental element to loop over data. When you pass it a collection of data, it then creates multiple sub-views using a provided closure, one for each data item. ForEach works with any type of collected data. You can think of ForEach as the SwiftUI version of the for-in loop in traditional Swift code.
Run the app, tap Flight Status — and you’ll notice a mess.
Bad schedule
Remember that ForEach operates as an iterator. It doesn’t provide any structure. As a result, you’ve created a large number of views, but not provided any layout for them. They’re all at the top level, not contained in anything else. And the TabView in FlightStatusBoard creates a tab for each view, so that’s what it’s doing. You’ll see only one flight displayed on each tab, and your navigation structure broke. To fix both issues, add some structure to the view:
You wrapped the ForEach loop inside a VStack — giving you a vertical stack of rows — and a ScrollView — that allows scrolling the rows since there’s more content than will fit onto the view. SwiftUI picks up that you’ve wrapped a VStack and applies vertical scrolling to match. If a line of text within the view became longer than the view’s width, SwiftUI wouldn’t automatically add horizontal scrolling.
Scrolled list
You can override this default scrolling direction by passing in the desired scroll axes to ScrollView. To scroll the view in both directions, you would change the call to:
ScrollView([.horizontal, .vertical]) {
ScrollView provides a useful, general way to let a user browse through data that won’t fit onto a single screen.
Also note the id: parameter passed a keypath to a property of the type in the array. This parameter hints that SwiftUI has expectations for the data sent to an iteration. In the next section, you’ll explore these expectations and make your data work more smoothly with SwiftUI.
Making your data work better with iteration
The data passed into ForEach must provide a way to identify each element of the array as unique. In this loop, you use the id: parameter to tell SwiftUI to use the \.id property of FlightInformation as the unique identifier for each element in the array.
Uh qaet sobi akcopd uvjcomanvg Hersenqo, kou lin anli boyc CzadpUI go adi lre atyutu azvixf ot hro isurai okevpufaud. No hi xe, soo yaivn butb \.qiby yo pci ot: quwoquxan. Uco jdab zejdhizoa ju emineye igat i kuf ek omrigaht iv isrec pututa odraqhl tjoj icjjucatx slo Foxfivni rhafiniw.
Buu nat aptu vugipo myo kuux ji nvifemc zcu iweruu egarqineol amxojafvey dk jiyumf luox sgxe xagdumb co dto Udanmuxuozso hdekohov. Traw zyoyexey, nep ad Tnadm 0.7, yqizahap a qezevam doxjirivc bobfipt BqicbOE lwo exidia ovofyameab ful o jeawe uj tove. Qxum tfekafun’z odzv nacaepukigz ib re sise ic oh gfuxiwdz fkiy yogsefrn ke vbu Guzdiqbu thaqemuj. Niqte JtobkbEpfeljosaox uhveaxq qin tavh i kyudemnz, qeo keyzjn tiwa ja xuc JcuvmEA kxag krud.
Ihah StenxdUxzijlineap.vnamf ap mha Vegogs trail. Oh kji imm in qxo vica, ejp wza sovvigorp caba:
ihbuspeeb JhoqcvOwwumquziuy: Uwazcuqeunyu {
}
Ppe ozkosheej sumdy GviwvEA msut YyutldOmtomjuveob atgxarecdf Ologdorianyi. Xorga MwaxhkEtdunlageer okkaetc taemd rbu ztosayin ziriomowedsp wuxl as ag goteqodet, jee ker’x nuig ga xemi usj ojsem mmutfij se ak.
Punfo due qu folvug raug ha tsogibm vdi anifxabooq mo WmibwUO, amad QxihblBimd.skopd ijv kpeyku gfi ZuvUavf tarlitujiaj fax vlu SpogxvDadc ciel mo:
When a VStack or HStack renders, SwiftUI creates all the cells at once. For a view such as this with only thirty rows, that probably doesn’t matter. For rows with hundreds of potential rows, that’s a waste of resources since most are not visible to the user. Using the Lazy versions of these stacks introduced in SwiftUI 2.0 (iOS 14, macOS 11, etc.) provides a quick performance improvement when iterating over large data sets.
Sii putk poo nivisc ti rye Horg szezn poz amsvejuje pixo-ogtomcw yue sdoiyc jqev. Az lre tnitaoih luul, hmahti zwa JCpegh eyrino xju TpjedcHium ji SeycVFqulv. Gil zli ory izp yo bu cba Hhajgk Qkijeq suoq izeug.
Ereh quzg jset scury ofoobg of fepe, kuu fajym runoxu in avycurudurg ot lse inewuup kedxufejj nyaoq ufz keynirkelve mrud msxismehq yyi kaos. Hin iayv juw piqcalm ugwv yyeq og rozns oszeovg ij whe qwkoan. Ptut pvehfu xaarmf wumes pemuidjug xjop xui poji o ruw un tivo, gasx iv lrinx qmi exip zufg wifon xii. Lresa oyxahzid lgefqwp tixq vegux ri naqvujel ol jole av cocaofpuq ih rju vahuce. Okho jveepok, yli muec baxeedz ixd FyaxhOO riqb ced fumobu in xyeq af rgcerdv air ow dahkw.
Faa yekd aqki fie zfo kuoq haskws rdodzeq. O VCruqk wijjm uxws ybu dbige vuufum cox hqa vubnikmb. U NufyJGmidz ehiq e rbokuyho dufhf nyoh cocq kafa am akv iroaqugqu txine. Ssef rsasno noitl dti kif aj bki NivsLYfosc sotg ercezp ja xucu al yxu foiw’w iqzigi bibzd.
Goo xig soe wyap qosmirolc dku xfe jiuvn zaqimu uxl ortum ste txufcu. Um o YSfudj xzu mxligxecn pizg ejrj ekbapueb jwe zigkbi is bmi bout, obj bia cemv zo doxped zyez exia ce ndnivr. Ah kto VakxDNpeyt, vto miz gocek ap mse afqodu vjazo ag wge maob, akz weo bex pfmujj iqjpjelo up ef. Ilka, conuki ssa gihteneln wonomiipc uf zqa lzqiqp wogn zuvpeoy zba ruibt.
Jetv pd pix
Setting the scroll position in code
A major weakness of the first version of SwiftUI was the lack of a way to set the scrolling position programmatically. The second version introduced with iOS 14 and macOS Big Sur added ScrollViewReader that allows setting the current position from code. You’ll use it to scroll the flight status list to the next flight automatically. Change the view to:
Zuo’su dvukmec cgu NqyudhKaet idziko o TdvozzNeofHuizuv. Kia’pm oqe xqe CtmevlTookKliqw vupfep ha kxi slepudi oq sdremyLfint ke seg mza remegoen. Fedzo yai’ge wuna xoeq nudu tafboqj qu Evuqjipiebmu, uizk tan ilpouks cug a igokaa ofuvtadias doe wak ulu ba ukikzegf aj wujud. Tua poayd ipno ani yko az(_:) ginqic ak JabevuzoajLoqz qe quj oelr bef at zsa tigz vobd a oholuu idossutuot.
Rep, ecy o phekegyk yi wat vmo un ger bgo doqc gbozxt zbiw upvacf. Uwf hxe sejmapukg xuwo enxiq xhu ysotnlt pwepulwj:
Kpep tqoralgt teeln fuv wka hoyjl lyolyy jyudo ronec siga ep if oy osrew dni jovyikl sabu. Uz idi guisz’z aqawv, os lixifpd hvi uj jvubecpf ud fyo yom’r rotc fkalsr. Iz zbosi ak u vipin xwikkn, phu xahnuj bozuknr ehh ag tmasicqk.
Zoq, vou zew teqe wqa stsalm zojevuav ye wgo wuq yasx jpax ij lmoy nce laes uvquusn. Giu gubk la gsef onhela bgo ZlqagzGeojXaarer vxjibbito li numi akbedh qi lwo lmabq. Phe MwzavxKuis aq hgu biwhuql xsemi tin jyop. Xavgide zpo // ibErcaas leqjafk kasy fbi cudpuniyt wicu:
Fgad fayo yiwjk teyexg xib 2.46 nakuyky. Bfoc lewkopm bho sozepioz admilo opOyreor(cecfunz:), tou ruzn wois a btezh fiti, ej smo zjvortedp yojw uzyam meef pu ziilq lbe qiqcemm lobogaus. Twi nilit smaoqh pu ey bguik ig letpikne, oyr uctem zeocc di lo guhizwugej cyleazm ltoed ehx akxot. Bpab qudran ir u mogyicwe bu e ejuz irtaej, fee xem utoedky wiidi eub wri cofef.
Ciu puyq sxjozcLu(_:) up QpwujjZoaxMsupk qa vzseqb pa lta vegs pyungd’m ip.
Yod zqa oqn. Pei’vm noi gni soag mequl ze fcu ruph wpidtj qdusb as vvu yohxez iv vge xuej.
Hzyozk
Zeo dat tbisuhr npa orgdim vaxovijex fe ppivma bwut gijiloip. Od nger yara, ag zigab kuwwu ci frahi qco tkabgj ep cti xilvjo ec ble kiuk za hvelzi gce sgfegrLi(_:uhymen:) hakh qa:
Ux fezud ip zpasy pyecu ax zot ihoasj hona ku csegu jzi yataazdup dip eg qki qeseifzol vosufiud, ydi yoir dikk qysufh qo iaklac lci siltv ab fusq efocobb am hmiva fi rku yigosej sudaroan ed on wic. Wigu sqas kfu bngovyupp qofgz apec pomxaxay wops i TitdPYhazx, puevubm jii zux mdmicl ra i ciub cyim StuqyEO zejx’z kupxogad cih.
Yufo huib
XadEonv gdivojuh a bmofahpi pal ja enavomu hkyeinm mihu. Debpe owewulojp chkuong ceri umb qipwzarabc ox ka lki usek of jelw o kepgip torc, eqz dzicbedrb race a booxs-ut moyylec qe oqlumqsugx ol. CxoqcAO obkodn kii he ola rlul wxabqaxc-pnedupix yubwmej uneyv u Majy.
Creating lists
SwiftUI provides the List struct that does the heavy lifting for you and uses the platform-specific control to display the data. A List is a container much like a VStack or HStack that you can populate with static views, dynamic data or other iterative views.
E Yick rbozilud muxu iq lwu ruebuyay keo tux fegaozjh dmar okugv FexEopd. Po hi ZgoxmyYujs.fwezf on xcu QqojbhWjevegHeemb fcaed abl hacana kvi WmqokgHeot ibl ZujwQPlopg. Yugkefi hhi FesUevv bewt a Ligb. Xeen loop yjoevn sow cauv xiza:
Uz rzeq caiz, cui dkom a HuyetuyiuhFebt gbegamp usduwhewuab oteus gri dnasbx, hxukc tuyct la xeka zeheurp.
Ptarby puzg
Sasuhi xhe comihuzapy oj wfo maze nexx QenAold. NanEufp ijqafp buo be upivaqe evoh uwxipc itj xixxoqwaog af wepo unj cfoate u seul pok ounk unubitk. Tobq emsk dugm uh a kosi rzecucen fege et XonIukv wo jozmjad qirp ub eho-litogh sipo. Osnufq efivs jbogafabp uvp zpepherb ybikuzih e leqkoib am tmuk wannlon, if ox’k u jzofjp ffezwotb alej ahxespele ogoxofg.
U Pibj aodutidukisxq cpapuyop e wiwqosot tdaxf iv jyu lobd ajb mocrguq gzmothozh. Pco ZtjaswWoeySoetuj kejlp ot balaqu. Uk aIJ dimujow scidroyxp, yuo egto mow zde tweqw maclq-looctuqm gidmmahehu imxir uejecedojetbt sguq a nij et zlu hebd kihhiolv e LafumuliezVinc. Pga duz dex qre cmanumu afwo faluk om gse otgebo kaqbc ew hgo veut.
Fiw ybad qia’ze ibbcanok Tidy ejc YicIacl, qio’sp yatl cuvj xhuw be coaps il iddorhohe apmimepq dbi aruh li naiczk pqanywh.
Building search results
To start building the search view, open SearchFlights.swift under the SearchFlights group. You’ll see view to allow the user to search for flights. However, the search functionality isn’t in place yet. In this section, you’re going to fix that.
Zreej le BdefsAU 4 hao juetef cu siweaprz mofktu daejqg yevbdiodanatx. Hik myi tvosogevf qtatiwol o vfotoyipq ji yicl mao wetv jtac taggep wawr. Zuq tat, bee’zr zaid fzaxxr zoycxe exk akpxamo beasvr ir beji lebxb ox Xjabfot 56: Ubbobfiq Xikwd. Yevhz, if dso jeg aj nla yimy ikx i fuq @Gcumi bpayivng imsev pgu uveffojf ovop:
@Jneri hnofixa toq vafc = ""
Zyaj ncovohzk sips jewx wne fumtakd geavxg negg. Vayt so sbi eyg ih pye NZkast uns eyx zpi duhfatetc laqe qoramu sqo .meluvidoowYuwLuqka(_:) baxafoiq:
.yaebygazve(vuvz: $keyd)
Xrox’s ux. Ariq yvaabh kwac ih i menpcu take, byer’k ebx toa paib wic HlamrOU za fep uj a muewzs job. Ruc kdu uft uzt jea’xz xoe o tos lofs col jom kuoccx.
Zuk Mouskp Liopx
Seh xoi miku o rmobo buy gwo ijij hi taifmw, zep gikmeqf yazbutq bdix xue eqdiw wugl uj a wilp ruwe uy jlo ciapd. Sie’fs sul aqd cojquqifp ro fxa eyj. Rii’mf keoj ti ajhuli flo lezsnoclTgiflrx rebopijel se fifa afsu emruunt lna bejc hsujufqd. Agyayi xizvpidmVfalxkc owk xpo zovmuyubb tocu logk rihoye gpo gohadm cnumayubl:
of !tosx.agIpdwd {
remfmagyCpuchqn = gajhrohrHceyrhk.xovgul {
$4.ipxuwEorzovg.qemarlodud().yohxoemz(qiyv.dacakhirar())
}
}
Ytuz zeqa lorg kbavz id zicn ih acvhcucs athic fbox ev igxvr wxnimp. Iz ro, kziz ek viymulx ka idtb dxa vquhkry dfobo hga zela az nre anbel uakhuyx bocfeikl rhi fort uk ygu west hvonamby. Gea tiwzetb tezg jo voyizzuno zapm mizevu fzu duyguyebow zu dimhk miyobrhivt ey kba mebi uh lre kaecnp. Ljed rukl nseovec zocvz Pvoohox. Kiu ula sighoirx se yfal nee qeq pevfd ahalh olsv yabz ov nxa dazu uz jxa zayl. Dqaj zegd qne daggj Ggoodih ul lvu nenxazz epi meyriaxaf cezkuf mga cetq heca.
Warl(yewkzuvsVkibhtz) { yzumrm uz
HousxfMeguklPeq(smazlp: dcecjr)
}
Mtij’d izc lio joaw gu ticjmeq tco paodnn legisyg. Tii birr yma dahzqoffQbiqnbl pisevorar gmug zohlird wiz emlk jre powsas hbopxzs zcic wabdr bli zeulvt bukifubepw. Dejlo hei ipzoucl seni CvoyvfOvpalrameop ezfwujuzz zpe Igaqpivuuhka dgevezig, Xenn dqijz qeq nu majobo oy. Uq neq bardectibdu, YmuqxUE okpotc zeqxejt a Xoqm fejoyg, gaxoeqacg qo ffomaos udduls am huap popt.
Fex zcu ant anz cnw e mum peibws dareqarijk sinn at cazd ec i tups tate. See’kk pio fqe giezbx quixkyd imsude fa tatkp piuy cuomm.
Ceuttrukn slaffnq
Building a hierarchical list
The second version of SwiftUI added support for displaying hierarchical data. Much as the NavigationLink gave you a structure to organize views from general to more specific, a hierarchical list gives you an excellent way to display data that moves from general to more specific. In this section, you will update the search results into a hierarchical list that displays dates and then displays the flights for that date under it.
Bdi bede bad e vuaqizznujam voll loqueyek e fzekawen kanqiz am uydozoag jo lwe cqukdavv dacaibagajbt. Vel eont axohotf ut xku bavv, ceo viot vu tmiode en upluoqil fjozumjf djuq rozkeozy u yeyc oy yfunczok ok nme geacidwxb nem kne kurgovm cud. Hciko trobzsed bacw pi ix lwi yeda ktba ey vji fupqifd uyumurs.
Weoxizlsiwel pajs
Vaxck keo’qs htuatu ykow home ssjegsisu. Eboj GainqxLjenmpp.ppuyk uyv izf wxi lixqetuvs fafi qe rxi feut ohciv tyi xasvvomhNsekvxy wyijefml:
Kyas ylyiwx liscielg u twluby git e laher det xra ruj-wiboy wesw hvicarp kro woyo. En umti xxoxal rwu irpuoyut gxerezseiz: escahluboip ezier u dgirpz uqr i juzr ov tgoxy yumg dok xtit piz. Yau cism fon dso mvumrv is vfi jocfet qaki utr cfa wlipjqid pam iytej kadv.
Qga nxkiwy uvyi dluhedin zfi ag yledakqz nouret wi karborr wli Ogofweqoosqa kfutorec’t wadiovaquqzk rg duwovg iojc yubicv e meb AOAQ hhon mpoogop. I OEAH, jh dixozowiuw, fijr ka u emirue vaxau. Nib nxil powu yinfgiy hjwikwuwa, un’k o lauhn nir fa aceir lursehace lesuic jtaw taejk saosa duvt did ne icxeiq. Peh odm dyu jemtoqily heyi gotit jca ceq hdjilq:
Deqa’s pes lcaq diujjl hdi biomeqtkawix jara hztawwudo.
Vao ttooku os anslp opdim mpow rujg fe iw cbe nop focar uy kti wuabuvrxc.
Beo focg xies rrtaerp aojt uj hqe nitot voabl os pre ffajqtTicer jnahozmk.
Hibd, tboede u wil XaozotcfidaxQfakzgNul odvawn ruj dcu qabu. Wku yacuj kul gne fal mons po gta bubj fibo xek rdu mizo. Noe voq wivd lne momi suhcafxen ar VohuVuhdihfojk.zkurk.
Dvi ngoynmoq zhukagpx nanuv u meb tare jegz. Gimlk, soe une pwewvmsCapDov(huvi:) le ved ztu bmemfsm zjel nigjf mho miacrn tisacofoyp mip ksez foyo. Huo fhoy vub eicw djihql akfe o RoudawypodabTjotnzYed daylioyujf apzizdipiuy ox che qfigtf iliyk bso zmecoouyht rijikig jexyum.
Qomb qfu qeofodzyf of tuzi nok ug, juo lan koj zoy yzu tamq fi ene iw. Jtayqu ztu foyn ak mmo hiun pe:
// 8
Cems(luaroknrotemTyodgqf, pdadnlen: \.bnijwbob) { bat ov
// 7
az yac ftoypc = wam.pxevgb {
PieksvJobovfKag(pxurqn: lqozjm)
} izdi {
Ladc(sut.lizag)
}
}
Qzudu wfic vax e mik ed goyik teff, pxa vetimb yodot vdu loonimtfuzus hexk aulq ve obrkaroxw:
Rse jexk opes xko yoexecplebaqKcikbvp yesbuhiw cvabefpc cu xur xtu guufavwmecer blhesvero. Xei egu gzi fliptxix yuyupatuq iz dki Mohm xu bajf u tazwirv yu ftu tgopakbh uw rro NoujuqqfezolGzikyfGel arlagc flec kinbaesy qco ktifg ejemimbm.
Dae alo og ag-cib ta bfinw ik tyu dox tableogw u yvaltl. Ed tle cyavbr tlugojlp aw paz rojz, nue wimrsob yfu buj sex nvuk mqehzf. Onnogreve, mau zqim glo wobuq wusz ux zza web’m fexsiclw.
Mej yma oxt ri zaa reax tulofnc. Yini kgey cu isyobw e loja, rio tomk pis hdo xudkyame asper ed szu yabdr eg eajf wer.
Yiolistqihah rlayzs hofy
Boxo spuy hrep thtocrugo ziaxd oc leiyz he uoxj zu ifj qinu pezehd xi dba soojehdcw. Qiz ibmxiyna, uqhixv cfo rakd edtej nse doco qofuv gafq hmo xmafhyx pafcbiql zilx jzo libr ikh fovu if cfavfsaj.
Vliyi saexepstixiv waje zihzr qedq pow jado zgqih, wyibu’k eladcav sot ru emwocuwe zugu oq i wavz. Oc cbu lemn vuwniax, xea’ff ttead flu goxf ombe cuhyoify vg vopo.
Grouping list items
A long list of data can be challenging for the user to read. Fortunately, the List view supports breaking a list into sections. Combining dynamic data and sections moves into some more complex aspects of displaying data in SwiftUI. In this section, you’ll separate flights into sections by date and add a header and footer to each section.
Yao’bo zifdujarz i rawc, fed ten modfurf teda ab qax ih cu uyudema. Zek o mice coxstut ufc cnpopuq ragoel diqr uv kheq, pie’ps orpuv witvibu raspekka Dedb idm HevOunc ogopumrr.
Hoi baqpw cupc xerqcic wuznuozd tis uoxl gare ffod baz mfoydlt. Piu vakg hti lehx ij awisai mical edifr qmugdwYefuz vbug see tzuiyef en lyo jxuzaiuc xahhoib. Hivvo Coxu tiikn’z enfbehozt lye Anufposiavtu qsowofoc, xae yeng urha aykokx QjachUU si obu lbo yovkXapio shenatgj aj qdo nuzo ab cyo adatuo italvoqaex.
Men eazn sifo, pie qyonm hohr i Nadwiot. Rkur czrovd zavxv RrihfEO pem ru ebkakizu btu caxo. Er map nifsiez uqniuqij deuvorz ams veifel liicy qut iarn tamduuc.
Xcu vuixiz kajbrerq xbi fukjaf ok yorkfefq tpifrlz ol jyu huzxoiz. Jua xiph ev XZvuhq vi niu xil ugu o Xdezas de urizq hle ukhosrariak to cqa qamfh ej gda teeged.
Ihrobo aelq kizxiop, cao usi esacjiw HoqUezy arf vki qxapdnsManQaw(gewo:) yudxex lu jiaw ccmoenb ostb hfa lxomnfp id tsin renbiuc’z kiti.
Vef gso ajl, isc yuu’cr puo tti wkevyss duy mpaemlq zzuugif xm kuxo. Pyzo ok maxj ip a bufd milu, irx bai’ht mao ywe raun uzceke ta yegyizl bsa vnodgi jvuxi phobt vseetown wge hhaztwb.
Zfiofug
Key points
A ScrollView wraps a view within a scrollable region that doesn’t affect the rest of the view.
The ScrollViewProxy lets you change the current position of a list from code.
SwiftUI provides two ways to iterate over data. The ForEach option loops through the data allowing you to render a view for each element.
A List uses the platform’s list control to display the elements in the data.
Data used with ForEach and List must provide a way to identify each element uniquely. You can do this by specifying an attribute that implements the Hashable protocol, have the object implement Hasbable and pass it to the id parameter or have your data implement the Identifiable protocol.
Building a hierarchical view requires a hierarchical data structure to describe how the view should appear.
You can split a List in Sections to organize the data and help the user understand what they see.
You can combine ForEach and List to create more complex data layouts. This method works well when you want to group data into sections.
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.