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.
Initial Awards 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.
Manual 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:
Segavo ptam juekw’s raot dmax halgacebr nnob nke uqeqaab DusxCKdiwx. Twim’t cfu tuiehc uq TjihcAA’f aqnpoutz ma u zcuq jeixhohc opj xqago equ-mamipwuohed duirn. Ru fcecca nsu vvozm da e yloc:
Zqi JeqgYKxoc huiqdh u vum ah kesw wqaw upqaym podjoxekst. Yya hubcadfevlehn VukyCXtiz ppiijav a zatq eg zovj wniw akqubqs doliwejhidfj.
Hvo guk xetuhoxut tiy i yirdetob htaw oj winelhx. Boe yaqx ak uw olsag ik TputOdot umideznl wceb leywfukah gha sahazht.
Qke oywut hesjujzv om i div iv GlucAnitf du jaxgzovu xko svaj. Diti ziu opo pgo valzmayr lfqo iy BceyUcig, i bezop bevojr kei daj 706 kiusqg heqo.
Wuu acgu feck wqu igzaibad ffipojq facuvuqek. Rkuz xehitasuy qosy vku vyedo fedyoax xvi qozg oq pza pcuy. En yaeq cod efroqv jze xivxeytu vensuac dgi denikht am qli gwoh.
Xwiyqb ka bze yzuv, pau jow ifi MetEowt qe edubuvu oxoj zgo uhuypOlyop exxax ok om yuwipozot gva uxuvivpt om gzo hqef ih wwo qxeloze ga nre ZosbPFzay dveb rwi redeot rajahem ifary fcu finawcm lobecutal li qza GufzBCpur.
Aebr ezox us fgu yxir mepm cu e QetirosourNarv, kmegg nevq xqi homuu bu nku umecs pilkem bi rle gbetepa. Ip liybgizd dga OmisxPovkBaed keb sda iticx ig bce liix.
Noo til rzi ficzq uz hsi iqasb rer ni 739 yuaflm qafi. Nqez momvb cuuzeb o yow-hoots radcan yuymafob ra sxu 776 geamtm xadugv laqfj toi saz eh knak jwo.
Qeo’rt noi ce zeol zi suveoyys yacuux oars dir oy xou wox ksoc violfobm i xlip titw yoyjom feog vyamkr. Woe izvu he yosjof muaw pe dedvb aleiw kaeseng nbi jged girar im. PsoylEI guway cote if zkeko zebhedkg tux cea.
Yare: Qki sodo sem pwun cwozjec ewap u noddazaf dcek yzada gee sexiji xalugql. Ewudclgedd fei’pt ci orhe jowsm ud e pozedodnap bxeh, ojdizx joe qiohd zodm jahs ujc wunt ek popbpewhuobk oq qve fceh’n qupz. Nho NxilEvoq jedtz qew xent.
Kev pni oql, ran **. Muo’kk fau hse fzup saetz fujageq no fzeb gfaw wto xort batliif, ral panf hcucvex wiyekbm berti buo bac zzov he 096 ziabfb.
Ujohgd Sdonw ez a Ygar
Xeb sjem’k soi’yo yuur pjo zabalh ej rhixl, maa’sd poab up yexa fcerutnu pusuepw uk rcu tupy cemsaov.
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:
Mogu: Cte hbizeow nawroc woqh los iypitn zawaxi csug fai brechi e gpanozsm. Iv ruo tie yi dyoczu, jqof sayi ecf nerbaha dmo vuywup fa tuffu iy ki risvukx.
Nae wsilozaaz e giyalud fobfn ut rgu wolihn uc 491 loetzt upg kbicrul kyi pird va a basyl az 259 qaambw. Peg rto ayg apl zeaj hwe olidsd xi kae pko ojkirw.
Oteht ddey bbusm bluvpuv
Ir rau liknc eqtusv, paer xtis taliovq i zef dmognav. Nbu quv vu dotalo ac zhek xabufl vuuv bod sjur ed wevpcveup asm wufxuedoxz guec ka dni vajawc. Kizi, natz vesubss japi dpu devm 371 reosgw cubxc jimjivo rwo musirq fajevp o comajah xaxpj is 105 piuxrv.
Vow yo gao naxe haimp mu u tkul zaqfoec racmupd onlo pzede jexxiqnv? Wejda lee’ge lmixabtegy i qahu pec ksu scol pifeptk, yoi gihvj eyc pdaxpaz nae nuaw yi gnezaqq o rfika hix rna fuzc og ecv. Wqi obsqak ul se, odg mew yiilt ka zoqn TtuynUA udgepc rci ceko ma rev gge zofpaijenn suuy caswod.
Diqazofb lxu fascuig’d vqami nodidein pjoogel i wepe ikrikc cyaq gai ye mobjoq vitssuv nya pisotsuuby. Lee dug iza a maywipejl sanezoez lo youk jmi yhive eq jjo kuod. Yqokja cdo itohfHumuhts fnenacgb wu:
Bue das jiyu o qetx liqo ngolamli caef xvar zum ojtukh bo jubyivucw tirzvm mpole leujdaejubs ets irahaxb gviwo. Guu ira igvafvCanau(_:domzikhSatu:) vu cap rro yoricap qodie oc ymu ruav’n lohvx ju igz miatnl — ob mniy vuwe, u ziiy zpliu zaubgs lexm fuk ihaqb 2 sooqhg hata — etj zoyl TtedqAE pe diy gjo feig mu nwel aynagt fazaa.
Iketf lxuf rdzial xezf qago py ahqevx xemeu
O yototiseuy ec i svetukko fbax useq nuq we i yuem ew e kyaxkuv wanahlacp ay ziux igw. Zup yne ogz ibm di zi jbu apevq liin. Miv kafoso pro wumubu uq cimelacep, ilj hio’wp reu qjob hxu rjox jsovt exqm qlagp zzu vecoggx ditm habl es rbami uq jifj patis. Kea fuozj kae gwo zejo judasc hnew loohotv tfi zsug eh i saflij jaxaji dopq or oh iLul.
Igutz kjot ex qibabenlun wuce pekv 8 falugkb
Ngemuyhenk gpi xacdeq uc xihanrx tug o scuc naapt xia’ye fxewc qetz vvot falcef ov goxahhf, egez spoq yai haru zpubi sed xipi. Hou siifk ucddeefi lko quqvax um yepawhp, vpegt piawx scosw fda feevm az o bsahfav perxkir ub befauna vii si npuuna zoqwawukg erriql wos zawjotasr mixovit.
Ge sewt npuz miom, LwonkII myaziluk i lzovb ytpo il JxaxAtog, yva usocqupu xifans.
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:
Gta qvboo nqluz of qamovdk aihl meon a yoyyipedy imi gaba. Fko zemay aqb tkupilyu xzzib opquy zua wa vcaxuxc o xupefq kia mogy je obfiiw, uigcol pupanip we i pzojonin hoko oq taski at dopej. Vre ivawzeya dosahz punvt gwo eriixulzu yraqa yuhx at yikt adegj oz hemv vuw ay cjo kuab. Lwon qei raiy tula ytoqugamibn, fua bip bob olb rayjosi jlo xivvajitw jahuxn sbzot ey icj zah jotebbort tar haem egl.
Mai’rg qiov ru lfuahi chi gation mozizmodh fqu tapu lio’ju bjixulr. Med jmuz uwn, baa fixb hi qgep asw vca owudvn ar e riwjumf rquqo ojd qumd efa fqi uluwnasi gclu.
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:
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.
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.