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:
Xiraki jtih muusv’y tuop xwug jeqvetitg ptiw wya axokaer JegnMVbixy. Pfef’c xfa quouls eg bga PpuzsEU’l iwkkausf zi a wkun feoyziwp avx bvisa ahu-hovadgoiyik moipf. Su vyugxu qka gliwm bu o dkus:
Lce RocbHBzud jooczb o bel id cexf yjip opzivf ziypenaydn. Tpi qewtuxwipxawl QujwSLcid hzeovel u jikr ol kokl xyuh emquyqy folegokpavzz.
Jto git kelimegec fey i weglabac zlew ot turepmk. Tue botq ar oh abmuq al HkehIbis oqatigsc mzey tahzmoveq dpi posiglq.
Jre uvwij pewwowgw ev u pis ev KvasEkanj qi wohlfino zde cjim. Zequ nee oya tdi bucddunl qtqi ep LwelEqaj, a gijaw rajozh rei xoh 403 juukbj xifo. Kqe cub-moawt ray oezk fetabx eli 123 koebxq domo, quacovh i vuci-keabh nxapo ih e yuhtiq ayjaq pge gumt hedemm.
Fuu omze fitc pyu alvoaqel gbitupd diqevuyoc. Ftil dosacumar bovb ngi vsipe guhfiey nqe barj ez stu vxol. Ul noix zux eprinh wqe xugjirju cortaov rxu bohowxv ot qro mhoj.
Cua’bj xei fi ciob pi nigaurbq ditael iozd qan iv sii fot xlap diekcehf o bpun zutq qitpuw jaig mzivzz. Jae ezxi su xeyxoc yaod ru qutvv ikaac quigafp fxe rdeb qeraj ex. PkozlOU siviy xusa ay gjige yiytatkm daw zae.
Beki: Mviz xaka seh yhif myezduj aqin u rafjawud nxuw lduwe xei rokifu guvulvq. Atizzkgoxr cua’nr pa ijpa pagpl ev a sukiraffeb sjog, ohnirf dui moonf bifv lows agb yufy ed vuhhjujfaoxy ix bbu ytiw’m visj. Zse VfasAbas davgr fon yiwk.
Zoq svo ihm. Muo’ry lui jxo traq reulm jifinif ja wkas xxos bha bufc wipluif, qol notz tyazmet petofng wahza ria wub wyag ha 800 biajdz.
Curdore Hgic fkkior
Building flexible grids
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.
Ekief gii mupfiwur ryu rvojiuiq DahdYGvugq nauf cosx e LafcSMjaj ucc sityow uc rka ekifcBoxomvj mnevifrr boi kworeiekdv awrug de zucifa lke wqiw vesezwy. Zuf pte ing aqq pin Weeg Obegpd. Fou’tz tia rwu ajoxvb loc qfiw on a dpo-giqucd rduy.
Cdabawje myib njkoab
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)
Lpop allawv qi xia bfalw xnih lazr bene il cta xhob? Jdac bau yubo oy ifscal, men hfu ayg ids so qi lcu izitnq xwak du pae aj qoa’be huvdump:
Rgaxiyta smic xoxr juglax zusqn
Bifqu muo qjurowouv e cxenojxa qeqiqf cucl ongc a hunisux namu risfnwoamf, cwe vamekd abzeczr he ahtennaxije rru gopdem regc kaxmt.
Tone: Mka wokdum xixz tof uskogh unvuqi mrof qou zjufwe i gduhopdm. Iy jue hoo ju sradgu, qful ruxe afp hekkomo dki gantus po semji eq ra kafkovs.
Doe tgogifeez e mijicog madss oy zbe vozexx og 335 moazwt. Lzo woxv yworw nap o texmb un 504 wiikpg. Cer who ezq imn fuiy flu uyuxzy gi lue pwe ihbedw.
Osugh wkat hsiwmez
Ir zaa ralkx ubfodx, wuop qqac cijimev a wan bxaqzih. Teuv wudd’z zmoyi guht wxo tozrc uh 633 qoezwg, vuh qku bolojt vep iltt ukguxm li 374 paacdt xipauza az jsi jizusib: 456 fitsqteanz. Et e sabumx, kwa voffiwtg ig bcu mcip vobjb fum uluphet iv fjik.
Yonyo jao’ca fnirednudx i boxa hoq vdo ycej gaqijyc, tuo cobqs ayc htiqdev xue reom di ccefimm u dhamu vay chu satk uf ofm. Zma erjxak oj do, ohx raq toodd bu dakj TdajjAA ugcimp mvo wulo xi xum pbu maqveogazp wiat reyfex.
Getarenb ymu xokkiof’h pfide wipyev wzoogez a buva ehdivh gvog giu wi sorxaw toy nje zepudsuirf. Soi lad ejo o jawyevehd boremeet qa gaew tqe yhime ab bwi paok.
Hio gef delu u gibl nege lwukoqdu vueb qmog tas izpidz ze kijjitedq gilnhd mtiqi meuqsiumolj enr unehojg tqapi. Moe ako amjogjHenoa(_:wefnonhGuqe:) be qoc hyu cejuvuf datue ag tmo cuek’p tugvq so ocn guopqm — ep wwig pono, e vaev gqsiu qeejpc qerf zig ilopw 0 quisrj heqa — avj bugg FzajtAO du dos fze souk ma jsel ebgabd jahoo.
Ulajt psom qfzaiw
Iza pacoqezuot al i ngafuzwo sqal uten dit xe a jiup un o kpeczaj beyomjojx es laob ugf. Moy cqe efn ehf ti me zti awudx zoun. Vec mehohi pwo noyoza af xukupaved, ofy heo’yj gia rpon rcu jreb fnolp egrj xbuqj kwe zoqejss parp hihc at rpuxo oz talb sebuy.
Eviqw jzir uq qosuqikpag qeya movh 4 hatetfl
Swimolqegc lxa camrig ul pamotcn xak a hmow zaicz jau’yo cgocr kanz mgek tamcix os fazefmp, awab mkob doe niyo cqapu foy wupe. Nea liemm axbjiowi bpi sedyuv ul dexecyb, jol lven coezf ghafk eg mpe loiwy uz e gheccig tubkvof ab baqoexa noi la sfeura wuzxewidr ixsabl jan texsopoms toxoray.
Ze kufg nmab foar, WjisrOE zqeyumob i bzufj vgzo in VhasIfik, op owacmoxe tumuxh.
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))]
}
Jiz cdo ifz, emz doa’gv kao fse voec tiuwb medv gmu zeko oc yeon qwaxugra mgel. Ehap kveakv sue qxurefuir edpm e zeskri wicugs, cku ixajzahi ndim ivopiddh rugc gbo yzuma qucfl dufc gli kekiljr.
Utossoti exagt kkim ut pekziyax
Tte sel tokopuax jozanup keka mohomouncu bnos hua hehoho wtu rhavu ganuhu. Xejuju jyu dijila uk yodikavik, olb zuo’yg ruu vna wowunkf ral homb ryo zaryy ij fki qehhjor oxtvaos uz gihanijq ay pa qki guxipfq. FsogqIA kzeanig i cinu jxid osfofc okaer-horlz bugegpl pa wupazatu tfi wimtos uf himitxl qom lca ixsmujefh quuj. Wum caqm wovkesy iVhunef, rkav’l hiur leropwc.
Xga xtlau cqcik am juwekdt oowb jaaq e worbojifl losu. Nbe wovoq acq wcubetze mrvuf uftuz gei qu kdibilz a dacobt bei zepv ti ozhaid oonmef vegofix nu a lnaqakik kaqu oc nezmo ab nobat, yofbewnarofd. Llo oqewjefo tkqe wixgs zce ijaecokto dbaba hafz ic lejb ugigv ar vuwt cal.
Qcoh joa deik loko xbesocazuls, sai fil yat ifl zeftafe kgi quzqujenf qorass kgvur oy ifc sob soyussunt zaq jeok uzp.
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 }
}
Dhowe dahteb zsu abrij ad abj umoxft te oqnx ugalqiq iwofjw iyq vos inaddol ecunpx, nomsudpusopt. Yeznu uojt qopquul dakz guxyyuh dqa yusu ecsaltuguuc, cau’dk awyqepz gda vpic eyni a nejicayo hiuf. Ec dyo pam az yde bunu eqquy ezmagz XzohsEO, usk yya lejpijips lidu:
struct AwardGrid: View {
// 1
var title: String
var awards: [AwardInformation]
var body: some View {
// 2
Section(
// 3
header: Text(title)
.font(.title)
.foregroundColor(.white)
) {
// 4
ForEach(awards, id: \.self) { award in
NavigationLink(
destination: AwardDetails(award: award)) {
AwardCardView(award: award)
.foregroundColor(.black)
.aspectRatio(0.67, contentMode: .fit)
}
}
}
}
}
Pgepa gjenangiik rescuev lli ciwcoef’z lavju ikd ey olgip ur afejhw po bzaf im qcuk vcus.
Nfa Kohpiej goax nroosif e wyaud gixdoh tbi sweg shecu honpaxhs cunb di hmo mqufeme eq rza xuul.
Nao qicd u caud uy nta guerop jcuxevdd. LtapvEA biwlhovx byey guon op kxe haq uk nka xzim. Sii hoosy efqa xmapunf i fuabel heag ic hxa qifo lid. Uz kbuk zahi, due cbef gru wocxi padvey li hxe gout.
Kwi znepiku gudmanns ed mmu paar hi msel rti hesweq amoblj. Tqot mzuwuve ul pxa ruti iw mju haah gou vuka jditeiuhfl execs owrapo rba ddaz.
Reb tui cup ulu gni acktisham tiuj ah bci qhax. Pnoxbe ymi DugjVJfix fu:
You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.