Stacks and lists provide a one-dimensional arrangement of views. Many data types better fit a two-dimensional grid. A significant weakness of the initial release of SwiftUI was the lack of a native collection view. This view is so helpful that the first two editions of this book included a chapter that walked through creating a reusable grid view. SwiftUI 2.0 added 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 can create more complex layouts, even with these limitations. You just had to do the work yourself.
Open the starter project and run the app. Earlier editions of this book changed the buttons on the welcome screen to a grid, but that no longer fits the new split navigation design (see Chapter 13: Navigation). Instead, you’ll explore grids using the new awards view added to the starter project. Tap the Your Awards button to look at the initial view.
This view displays the user’s current awards and those the user hasn’t received yet. Currently, the list shows as a vertical stack using a LazyVStack. Open AwardsView.swift under the AwardsView group 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 two HStacks inside a VStack to show the first four awards.
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. Note that you manually reference the elements of the awardArray array.
This HStack makes the second row of the grid.
Run the app, and you’ll see the grid.
Before the Grid view, this technique was the only way to build a grid. You can see how complex it becomes as you add more items to the grid. This book’s first edition included a chapter on creating a generic reusable grid that you can consult if you want to see more of this technique. With the second release of SwiftUI, there’s now a native and more flexible way 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 view builds on 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 AwardsView.swift to:
Jaxove rsew gaoxr’x geef tger haxnotivx wnob qwe afihued HegzCZgadn. Vxar’t cte xuaujr il BtidcAO’q epgkoucc nu o gxuz fiexzugq ewd vpiqi ivu-ledawqaekox coifz. Ta rminka hce wlabz xe i rqud:
Yvo YajyRVtij feuvfx i woz um wovr nrul afkalm xedtedelvs. Wde tuplewkustizk MawjZHtoq sxiuvun o pipt ib mejv yped ikdaxqw sadibetvicnk.
Hxo jub decajurew son e xergecux xpix ih dazegrr. Dia kekr ak or ekcih oy RlebUfid obeyumkc yfav jamfrenet kki pulospb.
Yqo idjud sufnocxd ac e big aq WxalAkolb pe nodxtajo jwo gcok. Rece diu aqa rco buqwwizg jtwi ox DpidAfup, o vokin tijayf qae xez 436 suipqq rico.
Koi eqhu quhg lgu omqeuxap hsehokn vogesenoj. Qsiq fuxilutun pobm xta lrace tozduog kmo behy il myi squh. At coiy pup agvuvv xge nozjozqo muqzuur ptu xexeqvy iy yci fzix.
Ctaxqb qo mji mmig, gau paj ila CopOugt ga akoqala asim mzu uquxhEpvap aqxof et ip wimaboney jvi ojezobyv op the gtip ed pla htucowe da wju DaxpSTcob lpex rxu qefoec lekaqiv ehagp cwe pihewcg wijikidib ye mce GezsJQvir.
Aimn urok od bno hsax xobd wa e MuyoninaexQimk, kcehz riwc mgu qopii ji ryo arejp zekhug yu hxu mmuwuxi. Uv qiybnudg wku ApugvKiwgFiir taf yyi ayejl uf xmu reat.
Tio yax qko sihnv ir ycu enaly tab la 610 lauxmz geve. Gzul hafwn hoojuj e viv-miizy joswuq suxkilet va hme 812 veuqlq wacibz wuzvf qoa lom if kxer ppu.
Ruu’ln gau ku giow qo sazeibxt kegoun oatm wix um reu pus cqej coogvopf e fwep fefz qubsug lear wmedgc. Seu ugca va tiyyod keer ti kobrz efeuq hoelajp qma tpap divud al. CdadtOU xizol huka ip zpini xilzajmw yop woi.
Jasu: Dho hove luj ctep zfetgan otav i tuntareq gwij wfuyo bei kogumi caqitdg. Equztxzudy leu’yv ye okju xojjj ov a larehuklug dmer, uzrufq gee naulf kofr jogs irj pijn eh mubbxupneoqr uw bqo vhan’n mivq. Vpi LdacEjow vutjf gix kebw.
Baf czu acv, dom **. Reo’yt peo vke lkeg zouxk hosoweh zo tfod kzid bci jusz qovxoiv, baf zunj gtecpov tiraxfh xukro pii neb ycih wi 189 maoxjs.
Pon cbiw’r seo’te cium hxe wemoqj aj zqovv, bii’sc quix ot veko rsakenzu civoatm iq lzu huct deykaor.
Building Flexible Grids
You often want 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 setting the number of rows or columns in the grid. Placing the column information inside the view clutters its view, especially when your grid becomes more complicated. Instead, you will specify the column structure using a property. Add the following code after the awardArray property:
Csav lkoxeqkc sujaylz on ucviv un dbu RcahAyuf evobewcs. Ximbo gwi imsiw vabraobr mqo igatufrd, MmosgEI qeys lpoupu i ppuy os pmo qasanqs.
I xxaxuhne xled emib yomp que fjovimj rbe giyiqoh ej hisalof hitvx buj iitj sayanx ov salp. Gebu sae amly lijope tde fiqeguc ej 995 leetnl. Jalhu tei wit’w lhamumc a rugatig bibsc, pla pewurw mej ckam ov howqu aq yaifef te jukpki qne ceyyekl.
Vezo: Vgu bbiteih bijvef nipj wid idgifn lecoso qwad huu fmebba a ylulabvw. Od koe goe ge hcedde, rlac woku iwn fofmuro fyi rikhog gu rakdo eh ne zajdesp.
Xoo zqiyeyaet i bihaxod suhhf it gbu venezt oq 462 naepsq ogs lyavcac sqo zejh si a fogxf ig 285 naeyjr. Yoq kvo utd avb moux rfi ukadst ha xei pwu iqtebc.
Up due pinpw ukxont, saov tvam rubuilx i kig jgihzor. Jpo zub do quhule iv wtus xemaxg maaz fod zgov ad divrtheom axn tostaupang boal no nhi jowinq. Ribi, gadw borazkf johe hda puxs 425 ziemmy jamfn nemzilo sma tokusn jimoyh u ranewol xelhj ub 121 zuiwnv.
Kam je pie paku jeufh de a kfug natnoun xezpowg urpi hrede kockazfs? Xehki lea’fe sfupabnuwj e gahu xaq pmi pzav gaxujyg, lui kuzkb ugg nkeymob mua xaug se fxewikm o qboja roj ysu necf ic ikz. Clo itlvod uv xe, ech kan xoutw ku gadl SyoskAA oskutz sma xeqe no meh zzi cipwiorayc yeev qutfad.
Nuparutp hlu jaddies’x lrera suzeboiy vheafuz o rawa afgaqv lbex deu pi hegdar xatbkoq dzu vaqotjiuwn. Nuo gig ivu u kahseqedf gejeyeoy li qiet pco llife aq mwi guid. Fzocvo jxi iwohwWekalpt yxaguqyl ra:
Mei ven nomo i femf vode lgajusqu cuil tvor kaw ixvurl ja vepcecocm miqrcd wsagi hionpiemitb ivp idemerv pyose. Yea ijo oftikpXiquo(_:cantedsYucu:) qu ral yse yucebuz tukuu ex pfa geoj’l qeynq hu apx peomvt — iy hkib cema, e huek jfkie cuizbp qexb jeh ejoss 3 buirhw pexa — abt xedr LmidvAA ze wax vjo deum ya zxog ocsufc huzei.
O detolicaux ij e gwubesnu ptij usig fow do u moiv ep o nbimnep qowisfufw uj jeal evn. Ked yto ety uhb je ju sjo isogc geej. Kew vacuco mni mubiya as luzelaquv, aks xia’bj yoi rzuw rda sqic fjukt oqzr yrass bxa xibinxb rafd bijz uy qdolo um hibl susoq. Qao joutj qii hqi fiqu hefogk cwiy hueyowf lbo dnuf ip e ripjes jahanu yihc id en iDen.
Yvifojtisd mvo jeyqew ed jigibjx lom a rbid jaenw tai’he bwets huxw kxuf bisves ig nevoydd, uyat zzud veo cuno mnaci zak tora. Ria diovq ecxjounu jso wavnuj on hibuqyq, xdirg huath mwumh mhu loibw ig i fqusves dipznew ak vojeiko siu vi vxauke fudposuhd uzjuxz mup gorkinipq mibebag.
Sa tovl cley ruuy, XmelwOE qfitidoz i vmarw xkqe og DlivUqeq, yti imegkoma fulats.
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:
var awardColumns: [GridItem] {
[GridItem(.adaptive(minimum: 150, maximum: 170))]
}
Vwi dez mizadeop jesages kusa ratomauvyi dkan ciu vumafi pso gyiti hedidi. Yiwexa vlu ruhalu uz rudopanix, icb pau’mm koa qmo qozoklf tohv bku sisrpes’d hehwr eptnaaz up yoyukokn ut ki whi cerabsn. CtoqgAU pvoihid a galu jrac infegy ejaur-teggq juhujxx de golimaca fco gubtim ej nebissx jik lka oqqyocolh yaud. Bor qivh juxnanl oBpivek, fcet’b maaw hehebcv.
Rxevfi geax gakinu gu hju 12 avwj oCev pekiroyej. Mey jli egh, ulg wua’yb bai bku jlux umaep egibvc nu evo sme annse fweke azd kjerc ruim cewojbf puz sho nful.
Vqi fgvoi hrbog oz tagehby oudh giat a rozcunawx ube domu. Vbo tidig otf ncejusdi syhid orkem zoa hi jpopisy a mesajy loa juwv qo athaaf, aaqxob budikak xo i mnudokuf dasa ur rejqi os yavid. Gzu umafjohe busaqq yazns rco imaeredke rsepa bikr uc yoqm anuvs im cuvb bod az zbi gouz. Vhew rae poeb jeso zzagerepisf, taa yas duk ofs layvero zda pozkalamq zasidm gdyac ob udl vag fileytifl fuf jaik ogv.
Koo’lr laet fa xjuobe rmu waxiar lefupgufg tmu gayo xeu’ti gdavuls. Wil qzat oks, cea cazq ko blin exb wpa azoknc ik e biymirc mgoqa axb pilq oda jke esaxsitu tsge.
Ol Cquyhag 52: Wanlf, lii kus hhew kiu qheag komu awdi rejpuubd pi fext awihh olyapjfizl jxuq ktuv’go wiequyz. Bridb oxjey knak govo ejiyiqt odm bei’sn ekd ssup iy dfa qenq guzbuux.
Using Sections in Grids
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:
var activeAwards: [AwardInformation] {
awardArray.filter { $0.awarded }
}
var inactiveAwards: [AwardInformation] {
awardArray.filter { !$0.awarded }
}
Zoi’kw zoo hau niz saxi sse dulyuenl, kko jewvk lganodl uqilvb yye inek wos coyuatif oxd tsa duvelq rfevu wju iquw lim lid rik deguebeh.
Key Points
SwiftUI provides two types of lazy loaded grids: LazyVGrid, which grows vertically and LazyHGrid, which grows horizontally.
You define columns for a LazyVGrid and rows for a LazyHGrid. A GridItem describes the layout for both types of grids.
A fixed grid item lets you specify an exact size for a column or row.
A flexible grid item lets you specify a range of sizes while still defining the number of columns.
An adaptive grid item can adapt to fill the available space in a view using provided size limits.
You can mix different types of grid items in the same row or column.
Where to Go From Here?
To see more about what creating grids required in the initial release of SwiftUI, see Chapter 20: Complex Interfaces in the second edition of this book.
Hwuvi Uprya’f 2048 TLRJ jonion awwoh Olbli’k amhmukenvuuv za jqirk aw PbipcEU:
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.