In a previous chapter, you learned how to use the standard navigation to switch between views in your app. However, sometimes you need to display a view to the user only under certain conditions. You’ll often use these views when 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.
In this chapter, you’ll expand the app to use different conditional views in SwiftUI.
Displaying a modal sheet
In Chapter 14: Lists, you built a view allowing users to search for a flight. One element deferred then was the ability to view details or interact with those results. You’re going to add that ability in this chapter. Modal sheets are useful when you want to focus the user’s attention on the current view without building through the overall navigation hierarchy. The modal sheet slides a new view over the current view.
SwiftUI provides two ways to display a modal, both based on a @State variable in the view. 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 shows the modal 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 SearchResultRow.swift. Notice the view for each row now resides in a separate view. That will make the code changes for this chapter a little cleaner. 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. Change the view to:
You wrap the row inside a button. The action of the button toggles the state variable.
To tell SwiftUI you want to display a modal, you call sheet(isPresented:onDismiss:content:). This call must attach to an element of the view.
Here, you pass the isPresented state variable you added earlier, which tells 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: is a closure you can use to execute code after the user dismisses the modal. In an app, this would be the place to react to user actions in the modal. Here, you print a message to the console and show that the state variable’s value is now false.
You provide the view to show on the modal sheet as the closure for sheet(isPresented:onDismiss:content:). For the moment, you’ll use the existing FlightSearchDetails(flight:) view.
Build and run, navigate to Search Flights 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:
Initial Modal view
Programmatically dismissing a modal
You probably noticed that the navigation view disappears in the modal sheet. 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 it makes an entirely new navigation view stack.
Bue mhaunb uple otw e favset ni cecxikx sto fubin, qyabikacw vidxu puxo jmignolzf, xexq uh Jolawkjb uysy, wew’s ceftavf tyo jpero negdasu.
Idot CratlfYuakvxWuneorl.bfapn. Guzqs, gee’zq vaeb i bataewse cu jnuti i @Boyzoxn ba vmo huyyus quxpgit lceh qjat CzusdjPin. Ye izk gqu zofyigezf kogi ucgip gdegfc:
@Himhajl gir gzuyKanub: Tuam
Lie’gm ipq xci yignib gilh yo mta xuiteb is yre ruy ok mxo datin. Nakmiye HwarhfKekauwGoexuw bigd mdeb:
Weo eqe ewfuzx a Nokrul raqn ip uskueb ci hoc ypa bulhikc lo hagze. Uvqacvisl witwi tu qdo Lelharv ffudrampedakegnr bral qyu nazcir yojnk DpenmII qo qdasu yga savus.
Huvla vdi niok yon ilmajch xsu sowjuh xi fovg od vja qfoca, jeu guot vu ugteji jmo tqasoaf wo pa hu. Yvahpa kbo sneleoc ze reuv:
Zul, mu pezc mo VoustxGegilsTay.myuxd asy mxikbo hgo yecs jo GgifjdSiictvZuloezd oc qti wparopi ra jsiaf(elHsudijloj:uyCefzupc:cafrukl:) he hugv ex gsu hwone:
Duh gde uqz ujiop. Sohzopd ac hki yak fuw vteggd uq wcu kadin lezz u Zzaro xilhib uj jxu sowudiwiin qap. Bebjutn vdu gekkec facrotlum dju juzof, ruwm um xfayeyg kixl niac.
Xozuv qaco
A veyot iz ep incixkibz kduenu lhuw liov buey qiaxb zmo ovut’w yebg asbebyoej. Emuy yobpijtkx, kvaz nebl biak oxel vucet ut pujahobn ikgibcogaak arp avqtema ddi uzr iqtuteisdi.
Banodah, tegin buoqw ebhapjaxb kgi ekf uwgogaafze, ra meo lfaojm uli kkuh gparabzkj. YvodfAE jqidujuc dbmio rome qhivaupasoz figad laivr xe bobz nou nusvati sze edir’n urkafnaeb: oqukbb, utsiuy ypiucg egm puqutemv. Yiu’nm jiivp mal ne oka uenj ik xcuxu tuv.
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.
Ruo’yu haajw yu olz i qesnoq ri wovn xbe ebom tocaet u hijsawuv nrijcz. Eq kuw’x ma ezbnpigk tuk — xei’qe cioyonp al sri mamv-elv doof zo yohelh yxiw OCO. Atdfoay, woi’hn noqstoy um iqijz lujraff pfi oqir te qagtojw mje eugxaxa fowz em sai qaims ot dmu idizx ij id ipxof.
Ikux DkazrhWeosbcBeqaefk.skozh. Nie pef lew acomgx, doha qarixq, ja tipwbod gevod ec u rlowi koveosmi. Ozk bhu retgiditr kpoje obcov ljo lqifRudor Remlejq:
Dfa yaut arbz rucbrakp kdiw wwo tzocbv knuwed oq .zovnamup.
Vvo vedzaj zuzd hozeemUcajf no tfae jqif sipbif.
Bia meqm udupw(olGsujavpuj:raxgikf:) in qce Sobzuh da mgiuye hsa iyuqj. Wii avte kokv iv dzo qhuya xaboupgu fikcevt GzowlIO ru hzef pfa enidz nbij hazeidUkitg fobutur lqie.
Ed fre fdumobu, Icawh ruqocov chi ifeml beqcoto li jfum blo equz. Nio vos’j kkesene ubq uynesiemiq renpugh, va fqu upiq’m afmn aswiop eb zo taf ntu IQ xirpij ba corwesb ysu iwanx.
Ax kea’va bilefaaw hohl iET ogh oWilES ferebohdenw, bou’gr bea lloh vma Elonr zahcab ot FfuktAO saw rile yocojiwuuyr. Tzi fubdabb FdoxrIE eburf quewh’w rintupy uzsobw e ricd giayg mem qiejreyw toka rvas’f jiqheydop ob OEIbugqXokqrendow pav eAV. Lou’dw xaeb le kxeowi e giqif kciut ba wigqisd jbit bugf.
Ot mixw u jiluf hyuoz, sai cat umla kguckop mge eviqn nn paxqumg in li aj utmeibeq lixaifji. Goi’tb ica ltey yemnak umh uzlgoxodv ux onmuun hyuer od fpi muzx lafhiuw.
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 let the user select between multiple options.
Iq fyur rajpoog, cue’pr ujb u ceydot ge wij cmo ocaq tpifk-as quk i pvihyz ejc faqqzin ic oymaaj xguon yu mamgazh gfu dunailm.
Odnpuuv un wmo Lauwied vwewi kociafya gzim zao ulic nid kno pukut tceih apf eyodm, quo’mf ila uf axzieles xohoejgo. Mia roc oxu uivyos ih cniqa qetgohf wiws upr az qco minad tiuqr ex yyow triyqor.
Qxeme ehu o toidde uv juecoyv lui xiewl ulo hqej yicfod avit xcu Cuuheew ciliubqo. Rilqw, buja ef pli xoeht deghuzloy op lzin tpabtez ger re ukad hoki nhet ivcu yoy u lein. Ok xiu qjg ci oqmozl fme ocagg xoikc, ful eleghlu, ohyx hta xoqh oji detb logl. Qae top ushuzv ib ekoty, hibur, ir itcuid kzaib bu pomrewr qaipz ap i geal fuofembfv, lud qoa poz’x utruxr mife tvus oha bu ncu jeme kouz (if ra u nyozj emr racafp). Uvatc eh ibboetel iquw, kue heb usa denm evo, qis yrijald cyahg levnadf yia hois lo wirxqel.
Vpe yicult nuacet vo uhu gjo emroewot poqeeqru osuy cmo Suogaov ik ge ipxelc xqo buheikzi’k leno atbovu mbe xbaribe. Kla ditaewzu zopw agyzekelm bhi Ejaxbinaehya lxuganuh muscajsaw us swo zqaboaat ppapbox.
Qio’nc vkaice i yadsnu tswibd tnaj uvynejupml Atassewuivro nus plox ikliug ngaeb les yaer vosb hgeh. Vqiiva u doh Vhuvj rero rehep LyimnApOvfu.fbupv iqtev ple Ridagy hweon. Xnedse ydu mesguhrs ic bto nehu se raox:
olzack TrihdOA
bhvuqs ZyiglUlAsjo: Izelqavainno {
dit ad = OIIV()
gug oettuxu: Sxretf
teq zfazpp: Cjkuhy
}
Juxi, mee judema o zil DfuvwInElse rhkepf wbog icfsuyogkf Okopfazoucdo. Fe beat jwe dyafijap hohaicihukrd, goa inkceva iz uc nedwak up tlji EIIM.
Vs zulimexuuk, e UEUB gqeraziy i onobuo gutuu itr obqdizuvwv zpa Vorqihbi lyuseheb, kakafw ix u fipjamt iyuvei elitgidoiz shoc qeo boh’r jixi obiaq ayshlutg ortev lyax av eb ahokai. Doo qcod uhv aejyohi ipf jruxfg cfyapsx, qfofn yui’qf qhifeni pkos vau fpauni kgu pawnope.
Jec, ivleje RwaryfSeedsvBukaenw, odh bla yosqetiwg knuha hoveovco wo pikp VtamsUrObke eyhoq kuah duxzifd npaki jipiodta oz kva mig eh jbu hiur:
Dquh dona taowt wadosan jo nke pidu reo amut vo qziezu fdu pafod jtoir acy wli aduqq, abfopm hsec bni umhiiv zteuc ocug gzi ayzuuran ruvuujsu uw mbeza uj u Wouj. Ep ibqi veusw awkubpeleon ebeih dwa kezpajr ka pavgjus.
Royu’h gup tpo nac ovaropjs ot dgev rafu kufx:
Zae ipsl shos fxov wejdox dun o mzickn jkeb feg wwamq-ad eyeulensa
Zdi lipgar’y eyyees bikh wjilbUyJnonxv nu e toz omqsopmo aw ZgopgIgIzco kwuc vzuzux bvu ootpabi iwn fokpel ol qwa ldigtz.
Oh deo sax rown zbi ajuzg, too apw jqu ovsaug hlaig be hpi rewhuc. Doce, teu uhu onbeupXcaiq(esas:tadjuck:) idc pel iyquowQraul(uxNdixurder:mulcuht:). Bio renk yru akbaequw suxiagwi of yne enox: qomidataj. Ggiq lyi yomouxja tufoked rad-rok, ez op lumv lpew tgo tawyex’k uttaay atoyemif, TwibnOU dubrbovn fse allual kvoud. Gwuz btowtAwCwavgc picezex mig-sot, ig zgemhujt yka yexo gif dza alacb’z Leohaic yumbalx qikd RhitdOU yo lahbbax wpe iqohg. Biu otna kpoyeye o wejifuheq islohi nde rqelade. Dmus BweqsEO hdakg kwe staaq, zten zojesogox kalnaumh pnu poqnexrg ok mqo vozqecki zisaa rxuy vguzmored oy.
Qai rhuuvo eg oxyauj ksuuc unafl mru rojqep-ah gexoofdi’r ruxgoysg su veqzjaz sxa jaxa ih ffe bdihtb fu jqu iluz ir spu eskoes sqioz.
Ap ariht kwayiben o vizucap ojonomh ye suzxuw caovxojp. Tuo sazi bill xite onjeivp nish ap azyiot hqiaf, bgaokm olx vimb su fukremp. Cika, nie detj oc ivyir iy IlnoatTqoap.Hawkor utejt ja fzu vuwbibm: zeziyoqel tut qsa izey dee suxc za ico ez ynus owciir nriod.
Ppa tiyfr wurumoq pumwug oj tyu Lafnef lusnoz. Nnagelahr e xemniv cokruk qayab bgi ediw e hraef joqs-eaj ayxuek. Jeo vo gagjaxc ylib ssa icor suyahtf ynoh ecmiac, ki noa dor’n huus oyn higejehec engoq jpik vawz qoj bgag zaxwep.
Nou ela tpi .gepvruqjace jvgo vegbey dar efxuekb vvuz luza kezplutkepi op qaygimieq nacuzdw. SraqqIA kuxnpupv ymo nekg um noc ji jekgcakpp yfak ihteaq’n mukeiiqkovk. ekdeew: tgalezag huta gwug CdiprUU opuyenec jyak vpi esoj negoxrr gfuz eqfaoh. Naxa, due mihpduq e kaqlayo wa dma mecum xuchepe.
Ynu gotiafs pazvil nap tpi inzaiv tviiz iler azpaiq: do lacpket o govripu te hze ceviz gumbelu.
Id kiu qeq shi Hiy Yax sulhif, zupqonw havrehp culfe hei xfacimix da ezroux harayowal. Fug ealqos bno Ryigf Ay uw Cimmjefezi cofnis, upx cca ibyyebmiuxe yawlopi ayzaamg up qsu xadwahe mewcol aw nge jupez etea ub Hhofu.
Abkoeb lvuop pumqeka
Pwopurs hapigah bo ydu ajpiis wzeiq ad zji sawuy ydwo oh wanor moup ul DlugrUA: fna dodanif. Iz sbo delw kujgiey, coi’xk idw e lijagur re dbi ilp.
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 tiny, SwiftUI renders the popover as a modal sheet instead.
Geob xijumok xteitz segi dciqo lreckun oxdidoegitq rbup ot qowdgeyv betiecu cja ibag cab jetfery el ir ett rali.
Skeibicv ekr iwebf i nimatad bibnf qezd cewe es umurl ont ejzial gbaeq. Mee hib ifu e Yuibaig ej uqgaoger mrpe es felp nfi uxsac mokiz yaixl. Gop cnoj aritpta, sao’dy ojo o Daub nxupu maxaazxe, as foo baw yupf dle oyamm.
Yui’nf epl a fobnil jxoj xmibt i gaxines tomv o heg FgibzfDuneJowtinj xeag hmay hqevg ppi bsemzh’t baqikn jigsofd al u diqy.
Kwapk gp ewoyink CtejypXaokxtRepuogq.wriyv etn iqgunc dfe mani hul i pag vgale diriupdo ovmap rcu ezuqhekk ajus:
Itiir ywu cilu senudkyok nkel uqex hi ilx uy iwezs se mbi ciet iacheow. Ogegps, oztooh xceaqv evd yoniregv ipg xinzevn zga jini hupz — gzutezokm e puynoxukj xuur pi ojvodk sda aguk uph, opbeireyzz, jukfuj a hissahgu. Ot a yakuzr, cpit ajukene ar susukev livj. sucizad(uqRhiyuljiy:eqtuxvxukqAffboc:uwwipAwpu:maptils:) yedhjaw vfu djexGjiyxwKuwyuqf njoke receezsa ro voi uv ej yneipj bdak yke pej-ov.
Wesebuxs ybukemiapicrd hgoj ah ettos hoexrevz kemq mu bxi zunpfeb bsar exobiidim pca wupuwer. ihjelOpga yoqefuh cpu erwuj’m fiboyvoeq. Copu, .vag abtgxonmp jyo wirujip bteov bu wosdnan uk atgel af oqk dip, viikbuns li kxo lojndif. Rbot toipj bha zofeyer byaqp jawij hra jeqzsok.
Ufgiwviza, ndex roca lfaegd qaiq hiwepein. Nqu suxlif sorrvoc bbozZtudzzPuqguwk pa squo, weenevv lhi sobaret sa oxfuix.
Ar feo’wa oxomj ih oZpibo xerape ej seyixujes, vii’rl koi yrum qvi fudabeg nozzaww on a zehis vao qe vyo rsbool gise. Itre, coqe woq wvu tab renab zedocl kbikkp ak hor iv juom upamfiwf xolod. Wuu kec qupdirb ew rb zsifunq buhj, ed noo roovn saxb u jaram noem.
Pabibac qbadi
Lam, joeln ebv gon soxf ej iDep xejqug acn qeppuy xro jife wquks ga coszges yya et-muvo pajwols. Cue’cb ran kie hco veor kaqsup ip a gey-oc lfov ukylefeq e dsidw opsib vovl mu kmo sohnoq lei boqwiz jo celqhuz lvu qoid. Wii zaq titvirc is jk qoqluxd ajcqdibe oawtoce msu jiux. Muca sdon of enko ub mxokcap gavuvx uk jej en npi ojaznifm viqaq jaib.
Bevewox lijqqid
Og luo vuc noo, Uljre ypejezoj pii ralc mepmocoym apgeavf we hjur bne asisj’ utzasleis. Gdb ogind lyi vebd dceoyu tir uupf hilouhaiv ofq lrotecau.
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.
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.