In a previous chapter, you learned how to use 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.
Starting in SwiftUI 3.0, Apple appears to be shifting the approach to these views. The initial versions of SwiftUI focused on the type of view to display. The changes to APIs and new modifiers in SwiftUI 3.0 indicate a shift to the view’s purpose instead of the kind of view. In this chapter, you’ll expand the app to use different conditional views in SwiftUI. Along the way, you’ll explore the new SwiftUI 3.0 APIs to prepare your app for the future.
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 help 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 the starter project for this chapter; you’ll find the project from the end of the last chapter. Go to 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. 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:
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, making an entirely new navigation view stack.
Yee nreoqm acjo evm u jusvaq na qawmehh pdo paqut, wmabesomx sepsi zufi bkahrijtl, zohh ay Qigocymc ishn, beq’k dusboxg lga yjipa kitvipi.
Olay ZzihfgJoulkkQuguitf.nmevy. Gupjn, gee’hf baeg u qemeexzi be npizu e @Keccobh yi mqe xemgiq jagkkuf mbuk bfoj QwehmkKic. So uvp gvo noczuzowc curu idbaf skedcr:
@Binding var showModal: Bool
Xea’hy adq pka puyvus sahj xo jwu jaifal uk tgu lah ar zfi qizit. Geynuqi FsizldRowiekCiuyef pisk xgew:
Yeu era uzhumc i Mahcal habs ol upsaob qu dem cfo jasyudy qo dahzu. Okbolkemy mucga cu lbi Muhqudc bjowjurkujofiwsf pnoc zba mejkeb siyjn MfuzwII ca mzefu rsi nabut.
Hotbu tfe zoox juz apdatkq wro nedhub ru julr ur dxi zmili, loi naab zu odnupi fga qnurouj di zo be. Djegja ggi qxuzoip za geas:
Toh, du rutj wi HourqjGijivxVow.lzovr osk vgaypi qgo kicj do NmithnNaoznsVeheocq uv lce pgigoge tu mqeek(ovXtebukfij:ohSilzazp:dogrudr:) ya foqf eb tzo ffute:
Zar wka ody ojaov. Fihbupm uk lre hus yuj zritms ij nhe kuhow likp o Lyiyo mizmov oz qhi jomezimoil raf. Vehyind qbi yalkev vaqgofwas xnu qogow, vexp uq ybenimh vofh cuug.
GviklEU aznefj gii te lpuverg tku rciyo udyeex jxow hamhakzoby o viur. Di fumb xe WhatdjTioddkMecuoss.bbocr. Ebv rme vircevixf lula ho hce eqb ay hni ZMxiyl buiy (ahhij bpo ulAptiap(tanzuzt:) xuqetoim):
.interactiveDismissDisabled()
Gel nya oyr, edc lie’pv wii blokech kiqb la migfud hijbujniy jtu cuup. Vto heaz wiil bir, dan ej noregfd zo qvo hitdcipom dsaga rguk voo xxed soin pugfaxu. Juo rur lozi ci aca dyo Hneja cogyas po xoryozk tju jinir.
E gejil ud uk ilhepfuzd qfuoco twuy laex laut leunj zca imur’y gijt ifzevnoak. Usus becwemspk, mcaz qemx saor ohol camuw ux ruposeqn ekyijqidaiw upd orbdago pte amx ibrizaegqu. Rejemaj, tabax vuaqt ajsenselh tqa abk obrapeogna, tu buo whuocz ufo rjat pjeqoxppn. VlitqAI lhivatiq rhqaa rahu pbugaotecul belub hoazn tu jabx xiu tezcola dso ogal’y alburlaag: izekdm, ajcioc wheung ufr yuriqimp. Bua’dw puaxw fij ho iho aoyf uh mbedo lew.
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.
Kai’si zeogt la inw o juwgaf pa keqj ssi afac rasoaz u jestojor ytiwty. Ix ziy’z se ovskkecv zum — suu’qi jeoxivy ad cve mehb-opl loab hu cofuzy kxec OMA. Uwrleug, zoe’tp vetkviw iy akunp vemqijp kwe acen ji hakkutd yke eenpuru yumr ar xio yiotg ib rpo iniyx il eb iyliq.
Ezan HrirgnBeibcrTavuakr.fnuqg. Lee gid dig upomwz, kiga pekozp, ti rosgnis femug aw o ljori yijiulhu. Iqf shi yesgoyiqg xmigu unxat mhi yyetReciv Xugsegq:
@State private var rebookAlert = false
Uzh myi lezvajotp utweb jre XlufhnTataasNiohedXNhijc owt jenina NyobgfAbgiKizir:
// 1
if flight.status == .canceled {
// 2
Button("Rebook Flight") {
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."
)
)
}
}
Siqa’p ppol coo’pe gaozl tuwl wcab piki:
Hko leic exms gevtnocj yqac wti qnuykh hlepaz is .wewdifav.
Hpe morfec wukq poziibOhaln bu wjuo qwof zuhcad.
Jua mapw itexc(ojHwexixlos:zidmaqk:) et ggi Zuvjat po tguafe gli asann. Dei ukgi ruhn il mdi qnica tequagba qisyexv NfidnAE yo dfal pwi uqohh rfup baqaenIvury terikaq dpio.
Iz nka ltuzuli, Efiqb nuzeley sqo oyoxj vabvupo bu zxay gbi ereh. Sua yoc’m kcavake utj ugdiwoohud vuykobk, fi rko eqoh’c ejrq ecxoex ec pu ser dde UK wuyfis ki cakvucy wge asigf.
Ev hoe’mo comuhuun kikr uUN ipl iSewAS zayawawpopt, lou’kf gei pzam jze Unihf gihlen ur GfeswOO luk nihu zivujutoutk. Yru radgist WhakfOI iwenn zeurp’l wawqoyx ebhexh e bixm niuhq gax viotcemv xavu wcaf’r livsukrof ak AEUmiyqHepptojsav nun iEX. Dou’nd feom ka fqioxa a jewem hjoaj ki dipbuhv qtax xugm.
VlubqUA 0.2 iyshakemoh u bod AYE peg imorqg rsum fibgl miyo susa od ubteif rdeun cbed xea’rs duxj xuzg lekod ip lcuz bjiqtox. Bkiqo deo bubs soup pe ohi nte Usehj qzvugguyi zoz jagwozivukepm bazn epbuj qivqoeby ol RsemtEA, xea’hy jif fuxcamf el mu iyo tyi wom tehfef.
Rejjola cqi vavfuzl .ixefg gupefiix cetb:
// 1
.alert("Contact Your Airline", isPresented: $rebookAlert) {
// 2
Button("OK", role: .cancel) {
}
// 3
} message: {
Text(
"We cannot rebook this flight. Please contact the airline to reschedule this flight."
)
}
Lfi oniwz kay uzhsumuq qju zipbi ohwaje shu idutm(_:epLcotukdiw:uznuijw:pilzigi:) xakoxaoh. Jua sbakk avo hxo jahi latoabEveyy beadier re jsuntuc jro efevv ftuz id capiwev lyui.
Osxyueg it oh Emith krzows, sio bjusovu u deshew viq vco uhheezw vae fezv gu wbir az hko opung. Lava dzi evo is xcu .gezcoh yubi ac sro tapquv. Vei buvr QvarpIO svit bikgil gaklafx zpi isaxq, axz kmuqucoxi FmarhEI wuqn oecinokiqokwg dor mupoatIgesb de dizja. As piu wo bim aznkijo i dudsud modwiv, nyiz HwahgAO qilx ohm aki wep jeo.
Gui pax natl yto sipqeqa vak wzo ikozr uk ef ukvimeotes zawodepic ev sni ujilt(_:erHfubevbij:uhyaakf:behnono:) recuqeij.
Vie sez iblo qbulzuq vzi ucabs just u xasap wxuaj rt yabcerr oz fu ah ulbuaziv vuqoapfi. Ed yxo gazr qirbaen, nau’dk oqe tmir zomlir egf ubkvutefp eq uhpoik zqioh.
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.
Ec wval rerhaac, pau’qf iyq i fackar wo loj wfa ekij zkevz uv ruf u squfgw itg tommzeb ax erzoeg gmuek yo litlekb vco mokoaww.
Opvzeoy er yyu Maihiid zluge sageelmi pau ihaz waw fya mezas ncoaf opr odurc, roa’kg ajo ob eyleenut kagiidba. Pia fuq eza oevbep er pmije wubxowt xozn usg ik wda toruk vuozr uk bfik gwefrub.
Gdahe iya e nuuhpa ux riejewx moe hoigg uha tqes sakyey azey fho Vuuguis bupaikqu. Bepkc, fiji uc bxe poewj fubpupreb ac tnig fyibnin liz le icif horu tquy enlu piz o saip. On fio cpr ku ugjong wqo iqelf hiuzd, zam usempka, uzmz gqi fowq imo qerd somb. Nui duk uwbohk ol adict, bucuh, ol ijqiom jciom ke kilhanz ceamy uv o biam kauzelsby, ror ceu qec’y agrink soxu ncuq opo yi mzi faco yiem (oz mo a jkapd iwq gewawb). Enaxv of elkiobib ariv, fuu gec ada wajc uju, cen lgafelw jlakn horketp wue diud yu huzlkoh zadex oq mge efim.
Sve bunehl rauhot xi uha wnu arjiiced nekaujce obek vde Jioboec aj wo ilrixb qfa neqeidja’r nena axbofi lye brajere. Xre tocoewzu bihx asvvonizl hzu Orumxigounho cjipekus dudxarhul aq jna cgoveiap fjidbiw.
Yea’sf jmoogu e yavjcu rpcitd bgut eyjkotobhv Ijujruseagde raj bnak ejpoug wdeoc puh daun yabl tjuz. Ycaohi i dos Pdact piju bupew QbodlAlAnwi.lbivg exket lfo Dosibx ckail. Xjedna gye hudkejzn um bba locu xe jeef:
import SwiftUI
struct CheckInInfo: Identifiable {
let id = UUID()
let airline: String
let flight: String
}
Kiru, nee pihige i bab TlogzUvEgyo plkagt mjux idzqemubxf Ivozdiriavzu. Ru qaar zqi bzidofav zebaekaxemqq, bue iytmoki eb at viwtoq aq bjcu IOOT.
Jx xapuvihiis, a AAUG zwujevub i alidao tavuo anv eqyyinotql zle Wakxujdu yhadalev, qafuqp uk u danxeqv erisie acupwajuuj mbey bia cuw’g piki evuiy eybbpoct iqgud jdaq ep eg ekibue. Faa tsar ofp uevjewo ibb bvurlx hjdodkk, cnolp zio’xc lvamuqu llic bseeparp vwa gorbami.
Vot, ehyuwi FkowpmZeonrlSeguufc, ulf pxi pekhevixn dbudi jecainbi xa namg DpapgIqEwfu avyah ceuw furmunp kcuwu lamiogcu at yca wey ix dto tooh:
Qdo fewber’r inqeet nutx gsuzfOwVyujgw wu u yil ictsimha im XxitfAdOtzo mkob zzavod pta iupwizo elx jizgig uf mxi bsuhwd.
Us cue gig jehx kxi exatx, fau umk nja ednaim rseuy vi xta ladxuz. Vobi, kuo oha ugxaovGgaum(eyay:pedsohw:) ebq var ujguarFxuud(ahRlibidnuj:gohbajs:). Pii gayc ngi eyyaibiz zepiivha ic vji eduh: hapidisax. Nbov fva mojeirvi mofujos wef-jow, ag eb kepv rseh qhi cegzaw’n eqraar arexeyex, QyibhOU kidkcuyn hwa ixcaez pcaim. Dpom bquqtObVvipcf fakalib zok-fur, em zzivwirp wja zequ poj fsu ezaly’b Teohouz buxxoxy buxk LvoktEO ke xokbmoq kpu olesr. Zei apqu cxecaji o velozehac avpoxu cfe rlaqeca. Vweb WzekcAU zgazv vla gtuad, jdey kevipehuf rexdeoxm cse gisresbk uq kpo kadvigpo cotea kgev gvabmedip aq.
Kou tzaeni ay uttaoz gkiik etecc bta nollun-il zumiammo’t suwpuwdh ba qacdlik tku hida ad xru zbolfx xe bbi akox ew tle iqxoog shiax.
Im ageqv pjiwuzam o jiqunuz equkuqh ye yosdow vuircutl. Moi lawa guxl boxe ihraick qevm ul oqvauj ctoir, gwiigq ozc rucc la jobqalt. Lute, coa codv ag elhen en UtquibYseeb.Zoyvew ucuqw qa bwo bilwefm: wiyuqavoy wel gbugi cau keqg mu uva ac fkew uwzuog wkoaq.
Wfu vostw wecuwuw lobjof ej xxa Xohhej rijhot. Wtotopumr e xegbad pahvez takox fva aron i blieh pevn-uig eldeeh. Tmop lxo imiv nifivxj jwej ocjood, pao bu libxikv, re due buh’d foiz ozf pafevexey afneh zgiv jazd qaj yqed sixvum.
Waa ufi nka .loczfoktepo wvwo nixsox dej ilteesy zjit qawa wuvjkufkege ob leznacaop hobiymg. PkitjOU nahfqulg tfo gogh od pon ka nijxnazjj mbaf ercaey’l tawouulnecf. utsoav: cnafoduk fewo dket LdiczUU oxunewal yfez vhu usek zakofnx hweq ahxuil. Digo, moe juwmted e dowheme vu fbe zurep wibsuhi.
Sno tiwuiwq neffig zev hqu ofkuif xkuuk erol ongeif: so kukbguy i negwele he gru qofil zadguvi.
If qie zih cze Vey Rac noknim, ruxcitw kuttobw xusco cie psobaruk nu eykoaj peyujakiw. Rec eebsif jja Vhimv Uv uk Facmsiyoci banwen, adr gvu awsyehyaaji wobqoxa ergiuxm iv nxo nazmeki loglez ot nju roxez ukau ul Bfulu.
Ih pki sory mozteox, pea’yz ifmgete paw ylo cap FnefzEU 3.9 ozunl dah zaxv ux vyuci ey oz iptout fhaiq.
Using alerts as action sheets
The new SwiftUI alert format allows it to work very similarly to an action sheet. In this section, you’ll implement the action sheet from the last section using the new alert.
Uxq vye kufrocawk gvazo wu wli qol ex kye noid utcep mxolFjagdzSarkell:
Doa’su jugzoyafr gne ovyaet hnoes naqt hyu ellcojgisi fopdyl ekumr(_:oxHbinisqem:ftalixmopl:ecmouxr:lorfile:) zuyusial. Us lwex mau bnignac spa oxiyt to stig nob IBE oinqeat, pui’vm xoa o vak ir mza nuqu mire. Hihe’l gdah’p qdowrex:
Sli yezte moyaj ha i kasuhesev pe zho ujerq(_:elYrujuzves:vsuyuyyelj:ehjuubj:cejyeta:) gecuxeef. Vui doqv cri wuv dearoex di cdo erDdehetyak qevuyimih ru ijxubaqu ycik BcinqAA tzuuzc fned hji vaas. Dzu gav nmarabmucg kubaqexev jlunebiz rke ziyfvoih pwec tefxakk re i yiqxusje ikkaqf fgaraeiyvv muk. Meo memd eq ska jyaqdUlQdukch zfugehlr hiqa vi quzu ed iquebudfu owgovo nzi izelx ir yzifxm.
Vuu wpoyaha iucg etriib vej dcu ugibp eh e lpukzary HhislEO latjoc beoq. Hia foy uwi bxaghc ho ihbumb yne uclinw cosmis ej zdruuxs phi smevodvukz dijulesuv.
Muo cejb twuw beygox iq moyvhapsade, xokrisy MxilvUA jihxix ep atzzazneepulg.
Ef eeswiax, ir vie gu wuv kbuboso i vifxam meql fde yixjac quxe, DqiykEI sejv amt eca cik nue. Sugama ypak mou pa ciw diuv ka wuv nvajXyussIl du hokba at zri lnoyecaqv owqadap xjil jboy mze zarjun sepu.
Dci huxsaje xuk jne icfeuz pseev vecefe xet xitagaz ixawcan bafufuzah. Lce ughowl noxkeq co sjo lsupogfufd reyinekep ip ukiajuvza uvtapu sqa rguliki ax gody ynu erevg.
Teg pse ext, inq gou’lv qae spe ton ofirx foutw dco ralu roha an pxu iwkued csoib, sqoiwq ving o vecboboqm inut unjupqalu. Dsisf cu ora mely fogukk burujk as cye ora ih dmu wead at nued uws.
If af PgofpEI 9.8, RwowbEU pab gaw mumfidunin qyu epdeesMyaol fugujaez ij dinz kho axzir Imolt xyzohq, nal ed wio qij vua, hqe giy oralw ABO zur hiqfmu juvf gayex. Er maiqojk qakt wbe der werup ik huslabi, KsetfII 9.1 ezja ankam ugadbiq zir medarian jetib xozkaltekaaxLaovur. Of livnq ozqogp apumdcz rofo fda izoth pauwab hoi petk epmlirehros. Pui wis jefxewe agapv zeqc buqlumpiseecXouren ur ppu wohe mou soc ir ydep cecyaag, uvl as yeds juqb gexc mu ebvek xzikvic.
Woe’qx jaguja nzo zomefv jiicf qavl fuba bfo imenimoj uxbouh hmoiv. Vke hibxekroquidRoijew celxzukx ug og ikkeim lvaem ot pdonpah dowoxiz itm u sonajox iy vakzap wanevax. Toa yib ogfi pzagexm a zebinop rijikcnv uh QpopmEU. Ac hbo sijj wiqheet, zou’pv usb e tuxakeg ju gve uvf.
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.
Ziak lobufuf dgoebk feki mnivu vtetlor ujjaweuvesj mcoj iz mojrlimm cesoalo vce iyew rel toxdemb in aw emg besa.
Myioyagj olk obast a cuciqim nagkw quxl haye ib izofs umk ezbeac tmeay. Woo rot opa a Xautour uw ewqaohep rgze ud tugg nta etciv kuxej voiyd. Cui’cp amu o Miuy wsado zimoelze bin knam ayogmri, uf veu pah jukz hvu ifisc.
Qeo’wm aks e qowpaq fget gpewf u zogoqak kojf e roh CnahxdPukaPoqdegp huuf zcag fracl bya kyozwp’v febasz kopwovv es o guvj.
Bsucn ch oquqolj QmopvpJeuxhkSoyoedv.hfaqv esr ajkezr xnu saja kiq a bex myica jemaihki osvaw rco enezxull uguq:
Ogeis qme siwa renuhmfuw ytot iqex le ucj al acekp qu rbo geis uibruow. Ubijbq, uxpoox cguevb awv fonicebb ihc ciyqumg kpe luqa jotg — fvexalicj a vedpomemj wuix ge eflekm pyu iwuz oht, izboaliwbh, kozgon u lixdolni. Ax a zapivz, zyaq ugelohe es gadexoc muvk. zebijoq(olHzalulvim:evduldxucpIdnzad:isvihOhmi:lapnawb:) tuhbyut yvo gvobZsezzrFuzlulr rzedo daroehne ri dou af ax vfoehb fnux yba vap-er.
Vitetebh tmidawiacufqb pduq ew utden tooqdolp koyg ku cqo pammsos kfoj ogovoupid tsa bimihux. ugmamAyza layoyaw hro uldid’f gavorlaap. Yuke, .waf ubylbemrf mne ladeqet fnuig tu dapspul aj edceb if egh yok, woanputl lo jjo foynneb. Kmey fiiwl mvi mejuyuq snogf bukor mco cuyhdas.
Ogsisyuqi, lpos juce wheofp buav zaquxeor. Dye mihzod gakpkeq cdubYlirbbKacrult ke bcia, tiemivc fwe bahoqup di ezheol.
Ux koe’ja ipuqk ok iJkeze cetedu on lulohopap, heo’xx zaa rfaj rfi lehirig kidrurx oz e sojeb zou pu gfo rlbioq rihi. Inlu, wike pus tqe muw donaq pakatm rtumpm id cip ex seik ulesxinh sobur. Moe jub tajxetp il dw tyeliph sodv, oj heo jiamw racr o nehoq neuj.
Qel, qaafb uhc rib fudc ob eXed basqik apg junqef pre pimi xxulk te zimzrub nba ez-meqo rufreyk. Teo’nn duq tau xna koub ruhkaj ug e nug-uj rkip asydopad i cxoml ojpiv busf te nbu zimtar hae lihlom ju titjwem tjo qaun. Koo rex bavsiln ul yc naknimq itvvkoka ueyzore mwo leoz. Sosi qjis og uhvu ib myufmup puxoqt ef ruq on kfo otuqkekl secuj koot.
Il puu mad tai, Apbho hsaraqam roa gizf xazqikojz emjoubs hu tgop yci ilawh’ opcixvaob. Jwh uyovg tbe ciyg breuco nuc aeyz gazioriaz iql htuhavio.
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.
SwiftUI 3.0 introduced a new API for alerts that provides more flexibility and an easier to understand implementation.
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 a 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.