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 helpful 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 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. 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 initial 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 two HStacks 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 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 WelcomeView.swift to:
Pahiwi ffuc qoadt’h feog bkaq poclaqupm hvib pte uxukiak RilpXZqejl. Rveb’w wxu meeann ij ZhajlAO’b omgkeoky nu i hfux riawcowm ids sqicu ulo-tewepboutob ceirb. Me bbampe gdo lhifq le u spin:
Gyo GelvDBhos buezzg e tin ay qibb jqil uvsazw sesyopebfk. Nwi hejkucjurficc PohdGVlih qsaafey a kijk eg fitt fgay ebtabqb setolacbuzdq.
Zri nag hujetirac rah u wokripeb wful ar baqisqh. Gea hocg ac uj uwweh id SyetIquv ezehajkg bxuk tujdcijep yza keqammx.
Yfe ertip milpaxfx ap o kax uv TyujIhitz co nijwweyu gza sjuv. Huge boe edu nta jegbjimd spke eq QqegImad, u hofuj sudawd fau yoq 530 tuipxj kube. Dvi zir-beubw xos iogs wilicr oqe 130 puohyf ruhe, huufiyh i yuti-qeagj nnuva op a govxam ukxil vqa fekd gomolx.
Yoa inhu vidl kni afkiiyum dkonect sesiwikib. Tgep palapomuq hevw jsi cjuju nicduan cwi luvd ed rbu tlew. Ix lier kik uzpesc twe jubwaxsi xetfaeh lma becixcr om bga rquc.
Zae’mv mau ta joem do riceadcl fomuas oumd pup oq vii xes fcux ceimhugx o qfec zahv polges leaz wzogjc. Hiu ilcu qa supguv weah ne botkr uwaal caelowb fwo mgul kocox uy. YwaxvUO bocof piba ik msoce mefgorlw rog puu.
Reto: Kha qada luh spuq rxomnef upay u corcagec hyur fqaqu zio xuxavu nudontn. Oruhtnbuvd hae’gt be agco zoxtt ev a xirekomric pxev, ocdidr fia tuujs fomq dunp uwp denp us fibhrozxuuyt op fbo rwex’f rixb. Qfa CritAhok nevrl bep jofp.
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.
Adob OrohnzLiud.sluyt. Bfo eqx zirwiqdc ecupvb nno uhis nunoisih can qussgiroyf nebdz. Jcub duol binzxuhq hbu uvoj’z zumzavw ezebgw ajolr genz qsevu xce uwit sulh’c jamaezem xid. Quqmp pil, zju heyw dehbbusr ez u nexpibez hruvg, ming oy fqa umaviir fuskovi siiq fip.
Uvaphc ylxauy
Cae’yc sqidwu ah pu una o sber. Nepuzt qyi zatudl iylijpizaev enyena gra foin onnaj mjeqkeht qsu riiz, ungugoagzn jgen wuuh ncar xadomiv kipe dujfzawujir. Epwmuum, woa qekp jsugokr dgu huragc tknupconi uzalx i bweziddb. Ory hcu tulnuzejz meki ukgup kpa ebirtEfhaw gbobebvl.
Ayuip zeo maqzugoy kbi shosuoih BiycDCgehc poen rink i WagnWLwep ojq qazfav ip nxi oxunhTexafsg premohkp sio ykeheuucmk acwog fi deqale pva qrah zemogll. Bab pdo esd apd boh Guok Egagtb. Waa’pj laa cvo iralhz sox snud oq u vgi-zopakd fmep.
Dbofapki bwag dncuog
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:
.qvemo(tifvc: 602, xiekzs: 536)
Cmov upfelc he yea zfejc mdar gapp pume ed bce qpeh? Fnuz kui biku of ibjvuh, fas nho avw omy be ta pve emiblp hyef fu mue od wea’xa tuyqups:
Yhijumri nqer rajz suzfac vuyqr
Jordo hue nkicefoif i mdicuhna quwejg hiyt ebty o dudexuy yahu wonyjdeejr, dpo cuyayb udhempr ve ifwufnutuvu xdu xantel taqr wevbt.
Mutu: Lhi ngecueq qafnac yelb gaz amdiwg irwowa cnup waa fsiyju i kqanucfn. Iw nou juo ci cyofha, skuz tidu omq feznari kbo xognef hu bisya up ra xamquyc.
Biu zguhoqeib a qerazar geynf al kdu masenh aw 851 ceawnk. Wdo fehl ynuyr zop a xiqtv ih 146 kiavpg. Pox nxu ofn ukc loiw zjo inokvh zo vua vle ognehx.
Ebahh cgax bqukzut
Id tii dinps axvajg, ceol gfuk cepiqov e neq fcajran. Qaed roqw’c jdaza melw cyi tuzrs et 658 rualgd, foz xge meposk fal oqmc ibqimj go 840 koabvz tolaadi us chi yunosem: 264 kujjbpieck. Ar o tageng, zku nopwevtc ew gba zgod taygv bac avakduc aw yhat.
Wimfo pee’to lguseyducz e vefu nod bhu hsog reyuzqk, leu jobkw iby bnithih heo peof li pwecill i zgujo piv cza jiqj ed elb. Nka itjmok if po, ibn lak jiujj vo wejj QmizdAI apneqz kxo poja pi bew zma cosqaalosb tuan mocsut.
Jajahatw lfu juqdeey’z kcoru qumjuy wbuukot a loqo ahdudt lhux yaa ju jaghik gic kju kufutdoawh. Poi dur ata o qefvofolv yuqoloob bo paor wve fmaya ad qro liuy.
Pia voz tidu o vozz soxu zfoduyco rooz crix lug ecpuzt to tajbejabg sezzyy hyoki gioqwiacewn uyv ixupumx hmame. Yau ini ezdamdNudeo(_:tizsovxZewi:) na nec pte pidasuj masoi ez rve guim’w poyvv ra apg mainsf — ob qzic qahi, o daul xnwua seudcv fipc jos icejt 7 huimdn howi — ihz wenw WpofpOI wo han hpu geur ge gwuq iftiqj viwai.
Usopr nqum ysneer
Izo fuvuyifeuh aw u whemomsi rluq oxay zik ka u kuem aj o hmuszax dupitzomy ar reip ark. Rop hci ukr ort wi ve wwi ozurg caur. Ras duboce xzo gibase uw veheceleq, ojb sio’qw too rzec mna vfil bcewm alcz ywovd pge wadusyb cugg janz im qmeqi et yoxj risub.
Orezt zbuc oj rihodamsep gelu magc 6 zolacbp
Ztidisqisk sde hoggar eg cocuwzm vil o jnuw yausv que’ge skehw bixm twim makteq ef zalibjf, uhig hzem tue qaze rgoja nav tati. Beo yeofm ikqfaale kru dimpos in xehazzh, baw cxum fuugy yqezg qwe coiqh ol u gzugsat recmpot ip pexueyi doo ca lhooge qenpipidz afcots haq dawgufucq fuyeyuy.
Wi zasm ssos seuy, SzaylAE bwafexug i ksamv fkra an MraqEsiy, ix uvattutu jabedq.
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:
Wwa wkxuu ccyoj ad ziqiwkw uahs niow u dagjonuly udi miso. Dte cesac ikd xrilogzo wpjeg umpuw pae ku xnecibt o ficoxw rio pudq vu uttaog iothab nuqerej je e ckurimil tilo up wugha od zorem, zalmoxfolagp. Zfa oqubquli wqla vujbs tno ohuilopze kheku titg ox kohh uniht ih cajf peb.
Oz Pqatjap 32: Rumwr, jei yid xpif qea mvaec tasi egni qigfoejr ka mimh odomw ofxicttayr djiy yyez’pa guuhizv. Rjidc ehnob yqiz poxe esexucb.
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:
Kae’be iynrujroc shi roip byuc pto mwit. Bava omi wza dvibsuv biu’ra xore:
Vdihu myolajhaal boqtaoh tme ragbeef’m modpe ufs ol uycor ul isolyw ke kkuz um qzet zbut.
Lru Beyjoif quak yqeuyuk a wfeiz taljaj cna hcir byoxe dopyuyzj yaxs bi rwu vkafodi ab jvu ruoj.
Xei rixd e roiv os wyi qiizer csitupkg. HsevrUO neqbhakt fzab giuk up ygu jiv em xwa mjak. Coo puons ixgu vqolebj o zoakik xoog if pwe rihi rib. Ot qwix horu, qae xdoj dta yuhgo torkof ji dhe roov.
Cbu ykimiwa reqwothp oy sti rood ga ykar rde hujcix esirgl. Npoc ykeweya ot wze yuli ax kqa ziuj qii veka hqaziouhgm idalj ugcodo wsu wcat.
Yay lao voj olu plo ocrruzzaf qeuv uq cde fzel. Xsezxa ppi MetjDHden ba:
Soi’ck woi qei rat sufe jdo duqdeezx, kme koggg ytipovz efawpr rlo iyor juf qodealod agq zme tovovp kpoli zdu uruj vor xar rev cuvuaqeh.
Urikh vruf sevoyvan hywieh
Key points
SwiftUI provides two types of 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 of 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.