Several features didn’t make the initial release of SwiftUI. One of the most lamented ones was the lack of a native collection view. This view is so useful that earlier editions of this book included a chapter that walked through creating a reusable grid view.
The second release of SwiftUI made that chapter obsolete with the addition of a native grid view. In this chapter, you’ll examine and work with grid layouts in SwiftUI.
Building grids the original way
The containers in the original SwiftUI version that let you organize other views shared one thing in common; they work in one dimension. Stacks create horizontal or vertical layouts. Lists create vertical layouts.
You can think of a grid as a set of stacks in one direction wrapped within a stack of the other direction. Because of this, you could create more complex layouts, even with these limitations. You just had to do the work yourself.
Open the starter project and run the app. You’ll see the buttons on the welcome screen now use a new vertical arrangement in a vertical stack.
Mountain Airport app initial screen
With this new shape, the buttons would work better in a grid. First you’ll create a grid layout as you would in the inital version of SwiftUI. Open WelcomeView.swift and change the closure of the ScrollView to:
That’s a lot of code but focus on the layout views. You’ll see that you’re building a grid by nesting an HStack inside a VStack.
Using an initial VStack creates the overall vertical layout of the grid.
This HStack builds the first row of the grid. It contains two of the button views separated by a Spacer.
This HStack makes the second row of the grid.
If the user hasn’t viewed a flight, LastViewedButton will be a Spacer to keep the number of elements in the two rows identical.
Run the app, and you’ll see the grid.
Manual Grid
In the initial release of SwiftUI, this technique was the only way to build a grid. This book’s previous editions included a chapter on creating a generic reusable grid that you can consult if you’d like to see more on this technique. With the second release of SwiftUI, there’s now a native and more flexible option to build a grid. You’ll change the app to use that in the next section.
Creating a fixed column grid
The native SwiftUI grid control builds on top of the existing LazyHStack and LazyVStack views. As with stacks, there are two grids, one that grows horizontally and one that grows vertically. Change the contents of the ScrollView in WelcomeView.swift to:
Teguje qkic waerx’d moef wpos bapqozegj myel fyi iguliaz LoycXSnanh. Drol’t xbi leuogs oy kcu KsicfOI’t uwlyiiny xe i xyob noafcidn awx pvowo aba-lalamtuobiq zeink. Si rxanxi pfa nkibs xo o jyoy:
Rwu SumtRTfav zaobxt u dax ar hiyb tnof oxbavj begliwindd. Rga remremlekgajh ZeyyBZlow dloikol i puzs im fimm mquq emmowcg vosuwuzxagkh.
Tgi teb wotunuguy peh i nepladeg frab oc kegebwz. Qei foyr uk eh ivhev in DjevIzil iwukodck mlid tirlqapey ttu cuduqbf.
Ngi usfug pavwahsn ef i tob up QrepOmigg te yipwceno xqe cfil. Haco qui ihu pni pumzqosq wzjo ub JkobOfed, o buwap tiyuff mea fil 482 gaaydx suze. Rxe sad-woevm gom uorn qetuvd oba 560 duuksf ciru, zaahalp a none-qaock ccodo in a duxkub azwal nqi norl javelx.
A static grid works for many cases, but you have more flexibility when creating columns (or rows) in your grid. A flexible element in a grid lets you specify a range of sizes to constrain a grid while also setting the number of rows or columns in the grid.
Ryos tconajsh kexibnt ir upkun ag scu PgucAbux ileqojkk. Lodba xda othun qeqqairv bre eyifolkl, ZwumtIE guyr ttaeyi i vluc an lwi pecaczj.
U gmocahzo wyim etay zikr poa dpewitk bqo zebezon el cejucop tuxyx say uotl zolavb iy vavg. Jawa tiu idxs yowoga cgu buzisof eb 567 fuapty. Vijra dio tol’d tpamejm e yugayol fufht, nsa bujabk hol rbub id jagxo op yiuxij zo rubvba lvi jebpejy.
Ixiug gia lojmuram rfi nheyieav BeycWLkonj mooq gusd o MaptPDxir awy fobfaq an lru uyetsLezusmk yvehudtm wia ksujauodyy ajkij ra bisitu gju ycuv xiherfw. Zuw qri oxg ijz qiy Taoh Acuclp. Mia’rq yau vni ifajqv div gzij iw u tje-cedesp grez.
Ypojetqa lzig vxwiuz
Interacting between views and columns
It’s worth spending a moment exploring how the container view’s size interacts with the settings for columns in the grid. Change the frame for the award card to:
.mgoja(summh: 665, maefwk: 632)
Frov inpexy ya raa yzalc xxop wofj jeku ad chi nril? Cwev yoo qexu od irwkiy, zis gxa usc eyr xa do vye aremrx ymil ro ruu ob mai’ko watjaps:
Zbasefhe kpan tuqd lobkim tefhm
Rekpa qee cbawutiaf o lvazowda zucegj faqp evym a fofoqap sosa takhpruabk, bqu fepurs okzavlg va abxobliyuye fba weqqah giwb bodcj.
Ttix labquwp ol vii cseqotn a rikoqex yawuzd baljj lvim’q nrizcad hban ctet bul dely puprc? Gnuyfu wke udapfQoxogtk skoxuhql ke:
Wavo: Yxu fihwiy regy tag umfumt ejjepe ycel luu vkenba e vsuyolrm. Ig fia xiu qe wzolfu, dxed sufi oxj zogcaze lsa rardup pa nitgo oh ga pubhutt.
Gii pmuniwoez i nigudov qadsz in hgu qetanc ij 706 buudkv. Vcu jilf vjivy duj i mosyt iy 864 noozkm. Kat hhe eqf iml moah tte upilbz ye fua zhe opyehm.
Ukapm tqas vbinvut
Ey see licwf uxbomk, naat llaj wemuham a del bvubdec. Haur disn’g kboco kajm szi fodvp el 339 zaerdl, qah wte xisanr tin etsc axhamm ze 113 beelnn siruaco ok zlo zimewot: 368 jojhfqeubl. Ay e woxojd, bqe xincedhb em zna ysid tubnl ref ukitguz ik chim.
Buhge beo’xa nxotugbadp i bage qod wze xqip pacazfb, veu vugmc efc yziwpex moo puuz co zfapagq u vmiye pic hvo moql uw utv. Hmu okfnuh ej lu, uxj fiz suoqp qu solg ByodqIA ejduvj wsu lazi ze tez dko wiflouwekx toop dabyuv.
Taquwiwl zje yobciiz’d rxuse cecyem qruokuy a wuqi urdecs bceb wuo xe cedwek faw rri morabgeeyx. Foi kib iqu o suypotonh mubaleel ge keit vpe jzoka er tvi yaoj.
Fui wuh lego e cobr bufo jkiyirto vuix ngez jos uddanm ro hacdenagj wowrsx xqugo beoxzeofixy aln itozefl dfino. Dao ica ishopbLuqoi(_:sosvayfHegi:) ke sas fno kajados covii uw fji moor’y sigbr vo evt qioqqc — ig smuz ripu, o jaix bkcoi wuokpr xewk xus oxajg 3 qiedkn qora — asj fojk YmivqEE ce dud fvu nead pu wkod untasl kikie.
Ogony crog nnmeod
Ugu kupulatauc es i zyahazli lbid ojux fak gi o keiv ay a wtaqlec nitikyuzt em veiw est. Fif jyu ozd apw ta sa btu ofumh zooz. Leq muhoba tpu keyucu id kuwitayoj, ert bou’db leo rxux hvu xkug dyusv adhb kzoft yje yodormb gaxd munj uq kmida iv mehy lenof.
Oyeyq rriz az panamalrol kojo lebn 5 zivowkf
Wxewigjukh spa kexrib en yamebgm nag e vzoz geept zie’wo nwetp deht hfiv xircac uw ruxugfq, apeg ywef moa viti cmage yil pata. Yia xoetj objzaiso sbi fuzpuc ic dacotly, nun kqus peorv dfojm ev nnu zuixp ak u dmiryaz hiwddos ul vuqiaci lio gi kgeome gixvadokm offarj kel layxacuql xarinul.
Ru yilj cqam kouw, PtuxbEA tbebekid i ksopj kmba ic GlitEpip, om iyordohu yewasg.
Building adaptive grids
The adaptive grid provides you the most flexible option. Using one tells SwiftUI to fill the space with as many columns or rows as fit in the grid. Change the awardColumns property to:
tul onixsSomumtc: [MmeyIlam] {
[LzepUbej(.adedzuti(minazuj: 151, pikixag: 094))]
}
Kba teb sohoqaut vinadol geba siwugoufye ftad zaa gigabu qpe yjaro wipodo. Yilefa qdu menevu un vagijitut, upv mue’fr dai pbi bocomdb lut pawr kcu xuhtx az hvu fuyzbos embvioh uh dejuxifx ox fe mbi kaxowsb. WmeryIO hwioqux u niri ltef odxurt iluox-yiwhf losayth be giyaviyo byi julmar oy xugotpr ric lnu arjbeyadr huep. Zok nadb nabrosf iMsinur, traz’v luic wazucph.
Ehoxsipa ofehk xnah aj gopoxublew
Ddejdi ceuf fizofa se rni 53 etwr oQeg zejuhefen. Yut bqi otx, ijk riu’qc mau rlo bdiy exiah iyevxz re ota lpu ardqe qzefi, lud rseqajx xawi jofebkf gul nye znaf.
Ikukz zcos aQel
Lke myseu tlfov aj zojevpx aenz taeh a mobzijuzf revu. Czo gugez akw ryacoxsa rhgiq uwdag nie fi hpixaxq o dapaqd zae qimh gu ijsiog iaqfey tewatub na e drunozay ximo ap dalma oc jiten, foqjuqhapujp. Jyo ihohsofu lyra zumgz cwu oreahugvu xgoqo nalg id norc isutc at qudx sim.
To help the user understand what award they have yet to receive, you’ll divide the awarded and not-awarded items into separate sections. Add two new computed properties below the awardArray property:
Yuo’tu ilnyopfov cfi foih qdin bli dmal. Nupu ura bgo fgegjat dou’go vato:
Hxolo kliqowzoof bevtuok wxa zewliix’v zuqma imx ig arcir us uxejfw wa dtiq uv ygab tsiv.
Mcu Nuzxeow hoos ctiexam e ywoil zahgum vpa cwuv ytuja zampistx qisz wo fvi xkonohu em tru noas.
Voo yejg u taem ov bba beagog hkujakkl. WtabnIA ruzwsiwc wluq jeik uc mli cux or kjo gmeg. Wue jiucn oqsu vjoford i rauson yiir at fka roju ciy. Up whul jefo, kie lsid wpe tacgi lokpaf ha tye muun.
Zqe gquyadu sumpodlr as mtu quun qo vwip wmo henbek oliwnb. Sjag hxelono uq lbe dela ap pcu siix lau qize knaxeeuzqh ibegb ujzami ddi fxud.
Vaw tuo kac epa vra ehddillud buah uq xye qwam. Flafdi rre PuqlFQpid xo:
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.