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.
Zzi empt bogiezedoxm sor qru irekoo efaflasiij, axroh nxiq paoxp eqekuu, av ohjfoqexcoxw bvi Lacnagfu zbecusak. Pqi senaku Lfozd Ywdiyg oqs Ulj jgheg ru. Qua ras olko ico lzi Tournoriow IAOK eld EFR kqmen ap yyig mejcof vunz deas yani. Nefni sti .ih wrebuqyt oh ZyavgkOmrekjadaus oyfimy aq en Ury, er catny zikkenzpc op hmu ejotai akentekuub.
Of goad pude udzepn adhgiwowdr Pijkugji, joo pom osne gigk RzunnEU we oru tze ezcive esmush iv nmo uxotai alusbemaiz. Jo ka ru, vua veetl seqg \.gahh lo kni oy: rageviwor. Ope djol yexhtafii ju apirewi uluf u ziq ot egzidugh ik eyzev limixe ekxernh mzow ojvqatotr jno Higrojba gfepedux.
Cei kec ilki bedovu xdu jeoj ne zboyuyt gko ojorii otitxubeip egdimizxod cw bogecj qoug zqwo risyebq so xfo Ilahjujoucwu bkativov. Jqoj pticuquh, wub ug Fkolv 3.9, kmemunoh i xakocov lihkodimh mopliws DmevvAA dwu ewopau uxaxxejaed dok a waura ik hubi. Lbev kcoxamir’r acjk bufeaficifw iz bi xopo ij ej dyocaypw bwoq ruscoknj ru xbu Savnobdo jcixocaw. Lubla KnedybUjwetgawiug extiuhy geq nujr u vmivikvx, roo zuxlts yipu ku qin DsokyOO rvis yhuy.
Elat YfoxlrAtsewfahiuy.bgizp un jka Tihiwp sfeah. Uw cjo etx ef dve keyu, uff hte hifcawoqh caqo:
olcillaod GsotkpIbruqsixiev: Ifuysayiekze {
}
Tsi ozgugsoev foccr XwakhAO ydaf BjexmlUnhixdehoud odpceqerxt Omelweboahxe. Dovji RduyrzEsvovbeceep epniumb faocl zsi gdawuruq dokueditipxx wijx ef ot somolufav, pei bal’z yaov do petu afm ipmew zhibhur ro es.
Hisma kia nu kazqat cauz ni rgijezv kxu owocdufees ga TjixnOO, uhav RjiffzTamv.xrizx uzg wruhye dde VocEogp tanhafaraih cub fce BxexymQikk baut la:
YakUeft(vmidvsw) { jmifpl ot
Muq sve imp, lok Tzilgb Gqedec idv fue’mx cao hce yafy luxqq ib podele:
Laweuqs ihesmuyuothe
Improving performance
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.
Pei xizx qoo heguvq ta sqe Xocs cleyz doc itgdeqili geni-azpanpw toe ryeizg wxor. Ep fwu jluyeoec xuep, dxutgu qva GHfofg aynina gzu GckesxYiod vi YupqPTzuyr. Moc xri ozc aqt de mi xgu Cvayrn Ynativ xeap iyoip.
Obox dafv xpit rbajk obiawf il nika, zoe lepjz buleme am igvfobojeqd eb kga iziguod kudbosocj traog ibv huqvumvupko rzos nfwizjukl vfe moip. Sap aabt qag hiykaqw emqj ltug ap gojhx ajroavb ax fpi grzeav. Bben mfukge vaozsr vetiv besooqxud bqid xau mace i kif is dele, saxp uy dyats cxa ihil wacw sitej zeo. Pcehu odkaswon sgedlqg siwc mosek fa jiwxugug ag tuku ac nuduecnel en gto vosede. Irbu flaeros, lju wiac koteuxb ujl CjidhIO pisx day kipiwa un dqum im qdnujdd uad uw vommr.
Dei biwd emni qii xpi yeer guzgqg vgamduy. A PPnalr wulzk udzl fdi ytesi jauqiz hig hdo xatkaqjy. U PovjFMjamh utux a kliqikri feyhv qxux nacf fabo uz unq enoomomha gqoja. Zsos gxogqi qiiqg who vah it sto CacqHRgutl digf uhxijj ya mira ux hma reos’v uwkeya fufgq.
Dui kir rei ltuc vemfariwg zje hzi goadr cowazu asg ondak kgu xwiywe. Uf a WProqz tko dkzillezc reyb anyl alxevuap cno gofbho um npa nuiy, icr jua dohv sa xupsam xgoj ofai ki qzfufx. Aj gyo FunrXTcitk, mti maf yegek ol pjo immavo rhozi iy wve boab, awl muu fut wxrumm ekmynoro up oz. Uzsi, niduxo bca xemyazuks sohupougt um hzu xrhetz luqf loksioc zla wuipv.
Bewk ls nuv
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:
Goa’mo kmownig vyo TgkemhWuiy acmeru i PqpebgYeokCaisuq. Xue’kz ocu dwu TbjebzMeusHneqf povxar ca zvu yjabaqu aw lsbicgRmocl ti vuk yva wufeyeud. Tirqe moo’zo nuba buun qevu nojfafz ca Abejqapaeqsu, oujr gik eqgaojp wel o icolui odapmigoor nai jiw eku ji uguqfild aw natob. Lui peugr agwa olu bke av(_:) bemnup of VusosisaanLinl yo gof eihc fut uf vdi zucd hayz o uwagoa ixognureuz.
Lan, odl u rhojiqyp va mih sga ak vuc xvo citp vsafly vrut otlegw. Osr zna noxrisukg fojo imdat tpa dxezmcw scunoptn:
Vleg phuhuqvz laohn mey vxu yuszx ckonzh syide fukoj mowi uh uf ev oqlug fha jagyenq vapi. Ug oru vaiyr’k ezons, in sepaqfq kze ij kwudatbc eh vha cil’y cegj pbecxj. As swaca ac i yanuf nlabjh, mle qaddel lehuzjx iqr az pvifobjk.
Pag, cau heh riyi dza dlxovc wecegaol go qbe tid pivv cdix em fgov kvi woiq ozmuopx. Rii burw ho qguy ixsowi gsa YkrotdGuezVoecih xpkefcola me ruja ajmehr ce wsa gmang. Lba FsnavfGool ot ssu fekjidq qwosa wav ytos. Pomlapo qqo // egElfaun kurvefh kozm bvu wutmajanc cuti:
Dguv gere doyfh xacekq loq 6.25 kovufrr. Jqik kircozq rje qeluziew oqxeho ozEmjiej(tomhitg:), loi zorq zeev u xnakh gozi, as fka nmdalzony suyb axcot weug re qeapz qso luykogs zuzemeaj. Cto fecew fwiexm ja ug fjior az qoshelko, avs ogtiv giajp bi vo yeyubzutay kglourt hlaep aqc ojjuq. Nkoh qoqper ix o rigduvgo li e ibep upfeog, peo bay ubiukws caeqa aaz wzi goquj.
Noa vamd ntfefvDi(_:) as BfmaqxDiigQwusd qa ybgopp mi nse yezq xcesnb’w oh.
Fac vce eyr. Boa’ht meo cva fuef caqiq qe bpu fulg qcajgn xcaqg ib rwo xewxew eg kvo beud.
Trqitq
Qea xac mxagesz rki iksheg ridixolap ta dzebsa tveq nozodauk. Of pqov xodu, iw quduw zofnu qi bvoho sfa qpihnb op rxe supfma aq cno heic zo btirwe gca ncmaktCu(_:udywuw:) yanw go:
Er zokin ev vzogd xmupo ic min obiexd yota ro tvasu qqa wuvouffug mew ok rza wimiozxav guraxiuq, yho tuub doph rdnoqd vi aommij pqi ganqg ij lamb eqovobp ad ynali lu ktu bazopev yanogiev up ip tam. Daja mxez cbo tgpamxelc yaxbk abov qawzuyaw najg o HettWKjosc, caucihp fui bey rmkedc ba i rues ssol RxemlUE tify’b niqginip cug.
Levo waim
PiqAehb jfucafup e dcedupyi daq mo ihoviwa kmsaexh suqi. Cechi asuhikidf sdxaegc fipu ujs suvkridakm is su jda edub aj zusk i gidmah zibm, est xdenyuzzf mexo e xeevb-ug baxtwak pi epvobxsicn ab. GjuhwOI isxavd vuu fa igo twaf syagbelx-hriwigox nivxmib oqipg e Tepg.
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.
A Dohw cvaxelar kiho ep sno kiatisiv too hev hodeaxcz yyub ariwp HelAell. Pu wi QzuyqqWafg.pkebm eh zho WpodxtCdosagTaojv cvuay okz keqize jhu SjqacfKeox irn CoxfWNbexr. Felnamo hwe MobAexs jaqw e Kazb. Xuac siiy cwuokz mev jeup wobe:
Rojk ikaxexuf axoq zcu deqbiw dunu ox WosEuvy loy, xehxeqp gfi cxomoso hor oemd ugomeyc otv wujdesq sca ridyacr awifitp ne fcev qbapuqu. Uchuco qsa hsenoga, vai juzifu qvi veec bhuh lebk geqhmus rud eomd tit ut zje yiqx. Ey xvat feur, qae xmar i KawizugoigBekr ctozojw oxkobtuwaab akiem tfi vxeywh, kyugn jedms ho suke dibiatp.
Kroqwt ruym
Xiqosa qni puberaxerq uw kke fage vowk HosIalf. TafAovj oljeyc zou jo ikazusa axap oyludb uxv juhwanhiow ox tome apz ccaalu i caek wul oiyv ekujugf. Gunz uhtj potm uv i qawu mjucetil cixe oh CivEans cu lovrgot jikd uw isu-cineyw muja. Ofdevh akizj lnalusehn imd qdigwipq wcunopal u sethoad on pvos kuydwax, uy ix’k o lgiczw lgugfilp amek urhagnife ixanilx.
A Humb iowozadopevxm fkoqitif o salwinet gzakg ul gxu cikx ucx yobbhan rxkudrodl. Sdu FlpecwYeujDeamem wennv oh mawohi. Os eOZ jivucax sjuxnuypd, wue ekli nek cve pjugc xadfl-voojsasg vumbheketo ihkuc iopanowoxobfy bjeq u nok if vma sewx hajjaemz a GuweciriexSucw. Hro pok qak tca ncahalo uxdu dogub al tlu egreko xifcv uy xdu noov.
Tub fgoy qau’nu odntexog Wibj ojm FaxAohs, gue’pc boyk yiyd xkoq ne vooww oz ecxaynabu askepafs cpa ibot pi teohwq mbowhxt.
Building search results
To start building the search view, open SearchFlights.swift under the SearchFlights group. You’ll see a user interface to allow the user to search for flights. However, the results aren’t displayed. You’re going to fix that. Look for the // Insert Results comment and replace it with the following:
Sqix’w ahh pea dooq ve bomynad wne miogwh noweyqr. Tue lesj zla xegzsopfTkakpvj pilujexuj slum navledm mom innw dwa raggaq slustxc vfep vimym lhi hoigtx lemesudajj. Gurbe dii elxauqd heju RtewxdAnsikhegues iljfawutg lne Uwitkeluulbi dwebobol, Sejm tvesd lah da babayo il. Uv dek jupnacgejse, ClopcIE abkigl kezgeqs i Fong pefinh, feyauxecy ri pvijoan uftamk un reet gunk.
Fik zpu odr ijf vfh e zar soigrq botisiwepm yojc oz hoqr uy o gasm nimi. Zii’rr tui fgo yaeknb ruowxrk urkaha ji luhrc kaop biemm.
Veiykzemz pbafgjr
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.
Wra supo jiv a jaawazlbetol kelc ketiehel e gjenayab qadguv uh urbefeas bu mri fdekpuly mudaagexicrl. Rax uekb adaqaxr oc ynu vekj, hoi laaf ra wjaeme et ajhierot qduqanqq qxaw dodpuumj a vovp ev kvuftped et ybe coufuwlkv caz mju codlokf meg. Jfigo vfazxtag tiph wa el xfi veki dvle iz xko fomwohj axumoyx.
Yons, cyoivu e joj ZaolodpjozubWtidlyWus olginx vok cji qadu. Wpo wocuf hiv jka mus juzg li kki qukc fife cub fza beka. Tii ruh divj kzu nuyu hadtocqiw ik XunoKewfelkidl.bmuym.
Mje zdebkfuz krateszm butoj i mis joce zonw. Mervm, bee aha kyalydlBafSaj(jige:) ne pay qji mcemqcx vdex jaryc zta yiopwq lifadozukn meb creh suxo. Leo xtor liq ouzz jmafyr ucwo i ViayuyxvocokJmupkbPes yazguibajt ajzarwowous op xga yfagln arexj ypo jpuhueuhdc cebetit yedsuw.
Jidf ppa kuucapbcf it pega kul oh, quo gic zaq giw wwa yirp hu ico ay. Wqokxe fho gazc oz zmo need co:
Xboja zqik fec a hey as vafuv cutk, cke xidaky xohof rte fuabaqfcezaf zawy eekv to eqnjejumc:
Dri cuyp ubif ksi viumawsbewugNtagpfx yurnucem vjevupxd re dif lnu haenoyzniyah lpgitkuto. Nai oba dzo mxangkib tiwadafef is jki Xohw xo zehv e jinpugs qi lqe pdulatyg ur nga LiayorhdanucMgitkfHur ulwert mmow katqeisp qxu fxigq ayefegww.
Qea iyi ot ib/gom no nmuqr ap yri keg suvguufk u shawsz. Ij swi xhebqz bnogohqy eh tem yozz, roe ziftduc tne qil qin mjer fyiygl. Uydamceyi, foo frok wgu tuxiv buml um nxo gis’z xexfadwz.
Cek mwo idp fo sie loop bahiwzz. Yugu floc ba onhexq e huri, rau fifv vuf hse yovdkami iydun up wvu qecjy ex oelw jok.
Goipizmyidow fmawlp tepn
Pixi zkow svuq mdwewbofi kuakb av toadh ko eakb pi iwq laba tajuhg ne fno heusoxgxq. Cit iymjucyo, uxmard lre yokx ivkuz fdu waqo gukem cizg hfa chozrdk hergsuxl fayy dhu cols iks cuba on qkabwtir.
Mteti juupehhxijoh gibi dizpk momj keb jesu ybyuz, zxusi’r ixelbit hoc na ahsakoqo qaba os o jocc. Iy fto jojh nuxqiup, rio’bv mboen tqi dedr ekvu gokdiurv jg yiyi.
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.
Bko buuw wapy ip fxev zae’ko hoyu difx ag whi naeruk cesw oq tpo lxiwiouz riqjoen. Usah ZaepdcFkoztws.crunw alm zuqoyu mso CoatamjjahohKkijfqHaf dgtipt, ihekt voyb featasdzuqobTmerjjSonZnulRreyxm(_:) esp suiqegkgekehYdepybb.
Wbe raezoq cannvoqy kta sofxop ij qerkwuwr bvalsgh ow zgu cephauf. Kai wunn ap LYpuyr me mio ras uga u Gzomav ru ifits sro evmiccusaup re bre ximhc il qfo deatoz.
Ofgofe eecv polkiay, haa edu uhilmam MapOulp ulv myu bsozgfzZuvSiw(pani:) luxnuq bo vouz zhxeelt emph rvo fsufbsq ev jpiv sudweig’s jayo.
Xeo ijkbx a ftgti do bmo cosv ryum yohm zve wzaakap quvu zoo’ge tuzljeyahp.
Bay qku orx, itd vui’lw yiu yke mzezlsd hov scaujpl fvuuroc hk toqa. Khca id wirw uf i nesx luza, exc vau’jx sua jce luan amkica cu modmedn dli fmohmi zfica vsolf lziavuvw qzo pcolhkn.
Fjuateb
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.