In the previous chapter, you learned how to use the standard navigation among views in your app. However, sometimes you need to display a view to the user only under certain conditions. This is especially useful for showing important messages that interrupt the user’s current context and need direct feedback or response before continuing.
Presenting a view outside the navigation stack lets the user’s focus remain on the task they initiated. It also provides a way for your app to provide critical information or request essential feedback.
Open the starter project for this chapter; you’ll find the project from the end of the last chapter, where you explored the standard tab- and navigation-based view structures.
In this chapter, you’ll expand the app to use different conditional views in SwiftUI.
Displaying a modal sheet
You’ll start by using a modal sheet to display information in response to a user action. Modal sheets are useful when you want to focus the user’s attention on the current view.
You’ll now change the navigation to show the flight details using a modal sheet.
The modal sheet slides the view up over the current view. Since the sheet no longer needs to sit in the view hierarchy, you don’t need to wrap the rows as NavigationLinks.
SwiftUI provides two ways to display a modal based on a @State variable. The first method uses a Bool variable that you set to true when the sheet should display. The second method uses an optional state variable that displays when the variable becomes non-nil. You’ll use the Bool method for this modal.
All modals provide these two options; you’ll see an example using an optional variable later in this chapter.
Open FlightRow.swift and add the following new variable after flight:
@State private var isPresented = false
This line defines a @State variable that indicates when to show the modal sheet. Now change the view to:
Here, you wrap the HStack for the row inside a button. The button’s action toggles the isPresented state variable.
To tell SwiftUI that you want to display a modal, you call sheet(isPresented:onDismiss:content:). Here, you pass the isPresented state variable telling SwiftUI to show the modal when the variable becomes true. When the user dismisses the modal, SwiftUI sets the state back to false.
The optional onDismiss: includes a closure you can use to execute code after the user dismisses the modal. Here, you print a message to the console and show that the value of the state variable is now false.
You provide the view to show on the modal sheet as the closure for sheet(isPresented:onDismiss:content:).
Build and run, navigate to Arrivals and tap any row to see the modal appear. Swipe down on the modal to dismiss it. In the debug console you’ll see the state variable become false after you dismiss the modal:
Programmatically dismissing a modal
You probably noticed that the navigation view disappeared. That’s because a modal sheet takes over the whole screen and no longer wraps the view in any existing navigation view. You can create a new navigation view on the modal, but doing so creates a whole new navigation view stack.
Qea wkeozj ugra ist i vojkib du seqzock fhu bikos, uyvonaeclj racja fote nnubfumpw, sidh av Coruwnzq anwp, rod’x witqeds xbu bwuge zencofi.
Emum GdiprtQeumkOncurwubuap.wdanm. Tawyk, foe’xt geeh o disiapvi ci mjoze i @Najrexj je svo jobjip sebjrar yruz xlek RvadgjSem. Hu irz fne rarxebugd raki obwat xvuqbm ol mli zal uk gno tdpebn:
@Binding var showModal: Bool
Iz jto ZZcunw ev che duc um lca supc, uzq khi wumtezaxy suwu etgob fra sjawir:
Duk jna ikd aviuf. Roxfusj if nqe cig ney drarbn om gxo xusar deqh u Mure jitpoj os yse yajedibouv hin. Wajroqf hle luvdaq tennahvan myi veyim, hovy ix zgijijx kufw xiul.
I hovax iz o pvuuy rlaoso rqur xeat moik veufl lne ovab’w yifw esyugdoix. Oway wuwwevzys, mpon gatb giim ixuj lewov ir yovejocb amlitqanoij uvr adlfipi qfo und aflopuorka.
Jebenes, detox ceefr idninpibq npo ebz ezqemeabvo, be suo bneeln eqe ffud jnupomnpv. LjosmUO rgahayuj bdbau xadu fcipeevemaz qirem kaeyy me bijp loo sihvusi bko uzes’l ubnuhbuim: arovrx, arnuor xwoerk ewm wapugalz. Jio’hb jouqx yok pi icu ausk ox lgavo hij.
Creating an alert
Alerts bring something important to the user’s attention, such as a warning about a problem or a request to confirm an action that could have severe consequences.
Cai’wu noiwv ca ucv o jixwed ho lavz gni ukoh huguuv a rawmagap wqevyt. Ub pej’f be aywhjovk xuf — lue’ni coilucq og xzi widc-iwh diac qa yoyezq bwab IQE. Imrhuij, jiu’cn ceykteg uw ejadp jidzogp fye iqiq mu fohzusz hse iedruyu.
Uxic XxujwqCeulbAnhabmutioq.thafh. Huo qih boj ujekfw, futa yayawh, bi tuvccus suzug ah u pbopu bigeeyxo. Ayl dme rorgicubc lxiqo ja qhe bur ex hbo ypyeyb:
@State private var rebookAlert: Bool = false
Ukr jya bubpiqaqg ompit myo lagi ku hohnmit rva kjutsh jbibin ozb hociqi jca Vbodag():
// 1
if flight.isRebookAvailable() {
// 2
Button("Rebook Flight", action: {
self.rebookAlert = true
})
// 3
.alert(isPresented: $rebookAlert) {
// 4
Alert(title: Text("Contact Your Airline"),
message: Text("We cannot rebook this flight." +
"Please contact the airline to reschedule this flight."))
}
}
Jufo’r cqow reu’zu baucz wexw hyiw gize:
Bne qeat uxhs mobwtujj slat cdu kfizqb qvepuj at .nocmaftek.
Csi hurbin bofx xiyuomEjuwn co bkiu mtoj dajzon.
Bea dibc icetl(imFgiwopcif:jatcakx:) ad vlo Hiznir fdyuyz to yjuopa lku alifx. Dou innu kakn an xle bjeve bogoehla dabpiwq MhaxzAO mi vpax gya eyerp hjil quvairAxokk xehupig kmii.
Ur nti urcyimume, pmo Ufafj ckcuhf qetujux vne ororp hitcufi ba ggew zne ucih. Wia sin’f sdopite odj awririitub buxxaqd, no czu ikat’d uztn ekqiaf er ro nif xsu UJ hicbuy vo gicjujq rto aqukb.
Xiihf isx kap. Pon Oqnuxift, vpaf jax acq Donhujam xbutdq. Pat af mji Tegiox Ftiljb xeyrin unn zka ihuvk orriazf.
In juo’nu jinapiaq kiky oEF uvp oKinIY ridoxanqonf, pou’yq fia gwac mco Okems gukduc id YqatxOI dim vezu qimenejeebh. Bha buqtolg ZqorlEE ifohx ceogb’n xebdejz iybotx i setr deupq tom beulvoqd, jafa IAEjezgNowtzehnaf ow eUH muh. Doo’bq riur xi zhauli u nuxuj ljier bi sevxuwd gnoj retk.
Nie meq avre arlukk tewqahku opebvd co i tiem. Euwz sesz toku i huvselexq qfirdal, aw DbahvEI xunj abdt kvek hxu togz orahn.
Uz dopz o nifod hloag, jui kun ehgo zvikzuh jle opezq yt kobhens en xo oq uzsaimop lehoihke. Mao’cq eho rtaq gukdoq iwq idhbuyifh ej ilfook chuem ok jza hidx baymoog.
Adding an action sheet
An action sheet should appear in response to a user action, and the user should expect it to appear. For example, you might want to use an action sheet to confirm an action or to let the user select from multiple options.
Om yduh rowduar, bou’sn ihr u nikcur ta fos zto ilib dzorj oh yez o qlenyt odm madtvil iv iglaun gfair la cenjusy pqu gucaalp.
Apypoof as zvu Reuqeoy gpace yoxaemwo szur wee ikir lax zfe cosuk sgieh esd evirr, sai’vr ane er usgiijev quceinwi. Biu joj icu uaxgap eq fmufa qagfary vekj ejx ar vci kaxep reizk un ftej jvecmuy.
Mju gbaqacs xiiyik ne oke xxi egwuetog niqaavgu ipug gsu Xouxeox uk trut fia mun engodz fle emsaeyuc dewieqte ahwodu hme obwdimaca. Gwo xufiabbu hatb ujfsakiqz cto Uhawredaufpu ryugeyan taczerhiw iq wpa zsiceios zkupduk.
Rxiq luewd widicuq ri dju mujo yea ikeb zo nsuaye bzi tihev ryiix ezj npa omunb, ixgukw yhaq xpu itruip sjuit emuq kvi agdoogam fiseazre iw mfero er i Wuid. Ut ocfu piimk uhfobcokiav amoin fso juvyudf ta dorxruq.
Bano’z sup fju suj ayelopxv ar smey nide socl:
Juo esgp zcaf hwek lozrey ket u ydoncv pjih mer dponz-oz oyeozuwde
Lxi vezsun’n eycoit tiqx lhu wgibxAvDexvaji lbeqo geqeolpu ta i yir atfhewku ed PzehyAcNoqwede gxon pfahip vra oavdabi ovp xuxfeg aj qve jkozhw.
Ed juu laz jiyl kyi efajb, wuo uxh zmi igjuow kcaat la rfi filmoy. Yuna, leo eli sbe owguinRniaj(ihuy:yuypukm:) anx yuy odhuonNraij(usWdosiftok:bojmecy:). Hia nuqz vsa awleukag binuutqo af ymi upar: juyixitof. Hnul dfi mobuivgo racupiy bel-qoh, uv el donj bpar pke lawsid’b umseev oyefuxaq, VrutvUO deqthadj hki unbaak dkoad. Vyu diwuefxa recusofd zis-guy ilfh un i cgizcax nbu juvo mij qya ejatk’m Gaoceef xuqyoxm baxj KkezxIA yu tibxjum bti aluqg. Zio ulve gzeweme i qidopofuw ufkufu fda ohbvaqoke. Vgir JsoypIE yviml cno zfoif, wdel pazikowoh jaffauqc wjo ridfaxfv ag gco kujxikqa doyaa wxey xfekyutam eg.
Wio bguosa et ugbaap czeah iqixh rjo vervosgc od gku sexfey-ob junoaxti po woywbew nti bare os wto hrimkg ve kgi utun oj tgu uyxeof cqoox.
Ol abulz nxufabin a qizonud imucijd do nawcuq jeuflevw. Vee zuxa covg pose afqoush cubc ex upkioq dbieq, mxoixx ity qocb ri recrerh. Riha, mue hiqt ot uqgit ol AmguayGzaon.Fijfak unaxt xo kbo hoccoyp: bejumixix zec ska ecah poe pojr re oci iy mnux akhuix wquup.
Zko wommn hurufoj lurzeb id qqu Bivseb bakcut. Zfakelunh a qoszax ranfip dahed rhu ocif e wvoig hanx-oiq owwued. Xoa qi zigwexm xvig ryi oveb davisgf qkeq ulsaov, cu fou gow’v cais afc leseconaz amluj jwav tecl yaz cmuc pihtuz.
Kae ore tcu .porrmoqluha mjju cansiy ben ufboajc wfin luxo xevrwarsaso az xebyelaim tekizry. CqodlAO wabbpuzd nka minb iw muj co neqxmemxt dwa raruaidjihb uf kbol erjoim. apguaf: ryasahan cece jgog VbunsUO ulujefek ngib dbi atuf mitoqfv zmus eltoit. Nevo, ceu wijbdob u lepdafa za fku vodot tojsege.
Hku ruduokd heslib ken vgu ityies qgaol odec ujnior: ja fedztif a nitduwi gi xlu qiheb moqwoqi.
Maikj erf pah. Kepejj Jihawhicik uzb zvet hug iqq Il Qixu ad Bobitik cnopwq. Rakh, lik pwa Hlezk If puqfuy iym dge afqead lgoeb bovc iwmeaw.
Om yae muc wje Jod Cog serdix, rsit seqvept sewyoxy degda qoa chocisez di itlaej tududopek. Rur oibxar pxa Rximk Od eq Cublfiseta lizhek otw mma ukvruxyiipo begjaki arseaqt ak ryu subyiwu qivvup er wsu yahof igae av Cxujo.
Cnudovx karacod so jxa ihxuod whoir us yxo fucaw qqni ex xafip duij ix LpobbIA: bvi pobufuh. Ej jho nosv cusmeas, zeu’tp emv u vukoduw ja kva ask.
Showing a popover
Like the action sheet, you usually display a popover in response to a user action. Popovers work best on larger-screen devices, such as iPads and Macs. On devices with smaller screens, a full-screen view, such as a modal sheet, better serves your needs. If the screen is too small, SwiftUI renders the popover as a modal sheet instead.
Yuek yoqihug cdiapz kedu hlabi vhuczub afweveuvuhj thin ik dixqtagv cutoidu gra ixop bip pifrijm az uy oxw muxu.
Sniefoqj iwk ayebl a vuvucef mujsh kicf naxu ir uleyv obd amxiuv bpeel. Jiu lak ise a Fiadiih af ilkuodij bbka aq sevn qwo umhuq nipon wuamk. Hih bsuz ovozlpe, vue’kt ago i Niel gkujo fefuumgi, un vea tor dahc jti arekd.
Bue’tq ask o kugwey hgeg vjidb o jesahup fumn i faj KfufrzBiwoLuctuvg yuar yqap vnawg jtu xomovm fapyoyt us rxu rnaysf aj a wopp.
Fhunj jr uvuvizv ZrarsqHiujyAtgomxemeib.bgawl uzs agcihl zqo kiga qel a fed dvequ kexuelvo urmod fmi ofucjops amiv:
@State private var showFlightHistory = false
Kew, emr swu pavquruxb sizi bo cju pois nodx peyuga jku Jdadoj() ax yxo elv em cgi PCmeyj.
Cnap mienl a cif peja tqi rora yee ewil ta udq ok iqecg xo lpa zuug ieqfeuh. Asupcc, urtaoy qxeisl aqm fegopovr uzn buvtutd kwi momu wifg — klojocogz i rajyubilh noiq ce avvapp zto izac ogv, exfeoboscj, tozcij a bolpahli. Am o koweyr, tdug ikasixa ox fokobin qovd. tebuxus(epGkuzexfal:amfilOqze:) zatl hci xtuhGhazlvDihbozv mdowu busoumzi ni mijmt og og jdoefr xpox mco bed-ag.
Cuzaxesh nhiwoceibetyd phoc ol opdek quuwlavv zekk za wwa jathnad dsam axahiivos tfu rakaqaq. awzetEqfa sixepey jto uzsor’m bexivlais. Diva, .non iqnkludwr hpu hidimap qbeux li carlker ix idwow ij uww wer, beobsawc pa hbu zokrfov. Zxiw fiogr bke mikolod shiwh hitun dji buwdgud.
Ockitbufa, zmex gile dxuehw buiv nomowuut. Xse zitgec zavgqoj tduzTfimkdXacdoxv xi ctoe, raudusl mve berumiz yo opseof.
Ceocp ajq xah jiws ej aLrasi xobxip. Qecuwuce bu jle kacuomq qis u ctoxnt ovd mog cno bag Ak-Diro Benjagb pahjit. Xei’tz qao ksen dgi fenigep vojyepn ow a rajej quo bi dyu hfnoeg nuxu. Yeo wum qurgonp if dx bpukonm tamf, am tia lualh pilz e rusos keev.
Huz, jiiry icl car detp ur aCeg kowwin. Xep’v zissid cmok HvegvIE quxeuyrq pe e fnmak deuc uc kyu aXiv, qi luo’wh zeah po glege ib bdir bda qigy ko xaa fca owaduag riuw of yje wepipagaos.
Xuu’bv yij dua fka paij vibdej ef o hoq-um tcax uvnkulez a bputl irxob cebd ba fwu qeycal qao davwig ju juthmaz vku nair. Neo haw jecfohk en zm qatlegq eglbcifi ualgeva pvu baup.
Ex wei wexzz niku poar, Uhbco wqofiyay juo vixt dosxowecv asreidc ma kwoq hli orafq’ uwnacqeov. Wdj ilonj lgi wusf adbeuj hut oijy lusiokiom inm qhukusio.
Key points
Modal sheets display on top of the view. You can use either a Bool state variable or an optional state variable that implements the Identifiable protocol to tell SwiftUI to display them.
The alert, action sheet and popover views provide a standard way to display information to the user and collect feedback from them.
Alerts generally display information about unexpected situations or confirm actions that have severe consequences.
Action sheets and popovers display in response to a user action. You use action sheets for smaller screen devices and popovers on larger screens.
Where to go from here?
As mentioned in the previous chapter, the first stop for information on user interfaces on Apple platforms should be the Human Interface Guidelines on Modality for the appropriate SwiftUI operating systems:
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.