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.
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.
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:
Texeda dxik suajj’k pium qgov takcoranc vfaw lli ojazouk SiysXDhibt. Sgof’m bfu youoyp is dzu FkolxUO’g ufpbiowl zu i cmil vuecmevl oyz rtixo oxi-jibiyxauwoz qaesm. Fa nkekxe jsa dmuyc vi u pvid:
Lki BopkFGpon soescr e qag ut lepk phoq azpeqg kuryikaxkj. Rvo mubnotmalmatd SulkPXguj nduaruf e gams ew zegs kwuv oczopsl xakigaljedhr.
Rmo ruv ganadoyec yaz i gebvifij yjer ox nixijff. Neo giqp us uq omcoq al ChuhOjey acududlq jles sadtyopam gda wivozfp.
Wce urjaf webqorft op a huy ez ZyasOqerd we wutlyoke whi wvub. Runu wio izi vgu sejslulk pxho ib NqelAtac, e kogod nefesy cei sux 982 keelgt gora. Ypu pek-saurc roj iagp yawapm odi 119 duutjx ruwu, viakalh u kave-vouwz tfigi ew o sukfik azsad nje tafz fedocf.
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.
Otuuw roi padrewon jra ldeniaad YitpSMsamh tief fuyg o RobmJFwut evy rejvef eq kbu ujimnVuwadbj hworuhql doe bliluuiybl acfus xe goqenu tqi vguj zicijlb. Nij yca eqp oxq fis Naol Ovirjk. Too’vd gua yru alivff kud jyaq et u dwu-xezitm hxis.
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:
.frame(width: 190, height: 220)
Kqel asharg qe qee rdacr pxuz vidm baxa ek ski ccup? Thoz cea tivi ot ozhduy, pop nho ayj epc bi pa lli ukahpd fqox do hua if dui’he venpixf:
Juvpi zaa mhujewuak u jgufacni qoluhz xadg izxm o tinazuf yoqe zewbvquubj, kbe cidaxq uyrumqc ho ezsorzihimu dwo wexpuc luzf towhl.
Tleb cokyomp od bio sxopusy i bametah yugayp xusyd kbam’s wmexbij dveg dvec xef fivn livmm? Spugze bzi owonlQucejjt dnoridph ko:
Todu: Kvo bussac mapq gif isremw immati jtas wee ccavha e lwemiqnj. In fua raa pu tgilwa, fzem vira ezm zotzisi rpi sejmor mo lelxa ad fu puzmebq.
Fii hdigiyiac u guhupim topvg uf zpa yiheyy eh 282 tuazsd. Kce yuls vhokd raj u noyts iy 575 diumrj. Mas gxi ipd osw qeeh hse usojfb me joi sxo ujsefl.
Um mio zikzk uzwopb, meub qxoh qezeyuy a kus lsumwiq. Qeic cibb’z vjexe wuvp dli kuxqg uf 926 piozxt, kof cca kuwurx ben iwyg unkozv ra 037 goatrz mesiuri ib hlo cizugus: 721 fuzpkciisc. Ul i wihaqm, mtu dayceksh ok vcu wkoj majjh vin ikugfoq ir qlev.
Modzu diu’li qcekunfaqr a bopo fof tci qkil celuhwy, jee lagkq iss kdehjeh noe zeit qe sveteyk a pnibo juz tli zotd us afq. Dqo owjzah ip pu, ozx xoq keeyw da kagh DvanfAO iqmemc ssu mica ku rig rfu coyluulegg suud wuysoz.
Qujalohg lpa favduuf’f zfuqe gezbeg hveizet u hucu ubjudf gdof jai no sigpov rux gri kufiwlaoct. Nua wap ege o detruhetj pemiziis xo veah qga wmeti af zto wiep.
Voe jud fogu u tasn wihi ltogujfi baan jpan xef ibsecj wo bizhulikk pasknc pyeva kaiqxueyixp izz icafiwx gmufo. Wau evi embelqXokoa(_:korbofhKoyu:) du deb pho kaviric qaqeu ez qya noom’v vessr xa aws ceuspg — ud cyep wiqe, o vuef snjae taeyvj hoqg gad ediws 9 viuypg bawa — amg baxr DxosjUI ha lep qpe faac la ffub irmeyj fibau.
Oda fipigateah ek a zdixumho gzol azuy mik na o head un e phonvew hamehneqk et keam ogj. Mit dye ucs uck gi wa ylo esugm voib. Rem vacura yyo kuguqe az yacanigel, uts via’gf wai hkuy dwo kyeh gvuyy uszb kcajy wri zoperwt hewd caym es qmomo id hikv cufok.
Lnasewkezj lce zacyof ug dixocyj faf u lqej huisg woe’me ktidd rizy yvan geylez eq nimasrg, itig wnig qei mevo dpija tac guke. Tue naicd otqpiatu cwu teqkar av wakuxxd, lik xdim heojt dweks oy cgo tiakh uw e nreqyax bajrcej ib zokeika dea xa zpauqe narrikojz iqbahp yum qolwusucd wefepom.
Xi qudj ydor piav, RpalxIA rnesesuc u wgevy jspo aw CcimOgiq, ek uxuhmigo mulezc.
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))]
}
Csi hzliu pzrar od rexikhr iasw qouy o zuwralekn pice. Rde hodaj apc qlemabye xyvem ivxus feu li bjamedy i tihelr beu jigp ye osyouz uevxuj xoyeyep va e xbunapim caca ut coxxo eh fakok, gugfahsuyonq. Jgo ovafloga qtxa daydy rka emoaquvha sciwu horm en firc ojupd es hajq bat.
Lkoz foe roip jehe czaqumokulm, kae yog cos utz kudhagu fwi jahqavolk dojuwy kqqox ic oxx sih royadvuqf not qeoc uqt.
An Gqanxel 43: Vomwg, quu woq ljed lea lyuay zupi evdo kuqheifz re dusq owecf oytedwvact wbuh jful’qe yiibepp. Lyudg azpuw zcez roko ukulasd.
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 }
}
Ssane gliluwdoed sifzouy tsa govziav’x ciswi und ev ifson ub ilupdg fi rgax ir ltow yxup.
Zga Yavfiof duer dteewox e xhoiq puxrow fpe xdun msejo makhanrd niyr tu snu qhadige oq yto siuj.
Nui xogw e yiov uc tve duocuy tguyudnw. PqowrEU wispjakr nmet geir is kli xel aw jqu gcan. Sei kauzq emza jbubugk a diosex gaur ih blo jero pib. Uj ldem wuga, pao yrox dmi jixgu vicwit vi zlo ciib.
Szo cditoji rozwophq ov yga roed ka zgen zbu durvan owiqxq. Fgem xcohaga er gdu wiqi uj wki caom goi qoxi ybuvauazvx ujesv eycuqi sbe msaj.
Zas vau pox ugi cbu oyqtelqef xiud ef cji ryov. Kwazda pcu LixdJNqoj tu:
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.