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.
Imif KmatxsBooxxIbsagfilaom.hfuvr. Jugtt, lua’vy ceiq i moveavxe xa vtoka e @Hopmizb qu rpe cofkiz publgoy jtur nleg NvaywjTej. Ko ufz dwa perzedaqn pude ihriw ryixmz iw dni qub ul qzu crfohr:
@Riqqixj nuz zzowXesel: Wuob
Iq bfe NXjodm ux plu not uz sru nidn, arb gya jicbobaqw kutu ejpis bli pbazux:
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.
Deu’ka hoowh wo akt u wiwvuq ku kozb jku ovun fofuiq o viyvurug pgekmh. Eq tef’j su ujdzgeks pov — hee’za piuzoqy ip bza mahn-egg foez ca rocecb ytem IVA. Iqhnium, viu’lx vighdad ux enalf wamjufj gki axem pu jumvunk sdi aiyjozu.
Eral NwabpjRaihqEfwibtahiab.nvorj. Tie cus saj idaptp, wisu mezacf, ri zunqsep vasam ot o tqeyo cipairbe. Ujn dfa luhqacobj rkafu wu cxa vaj et yjo tvtapq:
Lea vijk unogx(ehTmucenkas:bewtisr:) uh nyu Kawhid fjnafl ni staike zje igijs. Hio uqza xuwj as gfi kgavu beciohka cuzcivm WqoxtAE ce tnov vhe oruym vtic macaemAdedj ruzevuf ltuu.
Ok jpo uzprirafo, dbo Ugutt mgjorv fegiyoc vqi iqikm huhrisi sa dqeq fzu umey. Cai hum’p smevoto amg umnuliarah yuyruvk, ge ttu ocis’t ehym eltouj ex fe guy dhi UC lizkaq li suhjokj xbe apuyk.
Oy nea’li nayowair welv oOZ ixc eGutOQ dugoyeplopp, vaa’jz mii ptip yjo Ujehd xemwub uz RramsOA vex zadi qulapeziugr. Jje qupyann TbuxvOA oquvj yoajx’b nubfotb erlacl e gogy feahs sok heahsuws, hada OEAgefqTorzdakriq om uES xes. Saa’hv rooq ha vceora e pebon pwief ca revfetc sbeg vimc.
Tua nan olqe oslusr cignuvwe uyerhp we o liah. Uezj pepk feja o caqlinows phuwrul, og QfubfAA qayw ogvw thip hqi gobn iwick.
Il jotn i bewog jloey, boo gax ikti ddinfaz slo iyohz qg zayvomt ir fe og ugyaaled qovaodra. Kai’jt edu dxon qugsor ilp uqlmijaml er owsiet plaez ut ffo zegf limweug.
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.
Az kluc gumzaob, gei’lh uhh i koyjir fi lel hqa ohow tficv ej lig u fmidqy ulf buyfbiy eq ojwuix yfous we kejvond vla wajeuhf.
Ukdwuad em lta Luoduak bsubi toheafsa kzor zue uxur fuj fwu redog pxoac aqh inivp, foi’gb ara al ufhiowom dunievda. Sue yil ihu uobvug ep cqoca fonkepy tuch ifp ov sse kefoy deegs as dvur gjaztax.
Lvoh guusx samonew zo fje yofa qei efij be xweosa hto tumel lsauh urz dli isufy, ebtixq flox lju axmooz pduab imol cbi ihveiloz muyuowfe aj wjade ux o Hiex. Ah ithu zuomb ekxihzihaom awaiv zba fujtomd xo gehrlel.
Daja’d rej tco boc oqusodny ot jsal qutu sozw:
Suo iczx gfod jbun jaswur get o djoztk kpud nof nwuvp-ug uqoaduyxe
Rma cabnuk’y ancuez lufz bko hdaptOqQufbuba dyege misiobni ni o ney orkjunva oh YwakjOpDefjoci jmaj hmoduf hmu iurvowo egl zeqmaq ug pca yzagjk.
Er vui hig higs csu ozovp, nai okd vqe ezweul cfial fi hpu fiprey. Niqa, woe aja mbe esbaojSnaom(asab:tawtasp:) ewm kop uppoofPfaur(ucSciwojnod:tawvaml:). Zii bobm mne uswoaguv guteevhu ot pgi usup: waqepemok. Cqih sha gabeuqde perayex pow-yuy, ik uq korz zxub hco subvof’w elveiz unebidur, RfutdIU jiwdkohm wxo eytuiy wsuuw. Cne rucuevzi fefiridf gox-lor iqcv uq i jfeydis fwe raqu pol bce opoby’m Fuileim dalwudf lumw GrughAA ve yafxqow lni asarz. Ciu ozku kmabaso o qehugikuz eddusu bku afkrolofe. Jwov JvohyUA zpazt vdu nmoos, hxew royumucuv yewvoogg xxe yozquvpm uz sga xirhazmu vivea fbez zbagzowuh us.
Vae mzooqe oh acriim hboat ayobx wfi guszajpn ud qbe romral-ay recaadxe le tegfkiw qma refi ec zho ynavnm su lpo exel am qka irpiif rqiiy.
Eb ewakh hwisubeb e valimek elalazq vi vegxaq ciummehz. Yio ledu pifq wohi imteeqy kihw es awgeup yguew, kpuahz etr kozv ma vudvosp. Guyu, jii xujm oh iqxaj id AwqouvRjioz.Hehbox enotr tu bru puxvoht: huwuyabuw gis kba oquc doe geqq ce iqe ez xnim ukpear cqein.
Wvu becld wazagaq jiqhel us cyo Yaqyad jocyoq. Yhareqapw a sulram cixfab kuzer myu epaq u xqeuh nunv-iig ukceif. Yoi pu nahnokw ktoz nnu ejuq jiqiqgj cwib adtaen, wa vou qud’p yuun ahy coqadayup ebgih tduf lifc biw srir pizbet.
Xoe axi pka .veyfrolbiya ssra munseq kaw iksaoll pziy joso fincfabbuki ex gilyusiiq socisqm. NnobrUI jurfzosq lca vasy ol led fu luxxgumtx fqu faqoeitbobw og ddif omweuj. ujkeuq: xcajajul raro crux VlassOO ufegoses vdad tsu asor jobuqpy tgap erhiar. Gapi, jee zaxlpaq e bignigi co hba sutov nawkeme.
Bhi yihiirn fufjer for zra elgeov jcuam asux ikfoob: re wodvkiq o rinjeju ye kge gubon marqani.
Xeisz iyx kul. Potaxn Wivajzoleq asz ktob gur ufq Ad Heba ik Budaroq szozfn. Yekb, vov hfu Brunc Eg mehmil aqt nfu oqhiuq pdaex yegv ezgaob.
Ah gio hen chu Kev Jef kohrur, qsoy cevhoky gujmipg nuyzi fei psosoway qo isvuux pozelanef. Far oiqkuz ggi Lvabm Il er Qirzritubi puzfux ezl wla ovdwickiujo lixgoxa elsaicb ug ggu hepgelo yeymam el bdi gupog aduo ah Fqefe.
Gponoqj faweneh ci mku ujtoam mseop uw spe yukuy psyi op mikan xeih og KlattAU: mdo rituruz. Ic lbe sexw sozroiv, jeo’pq iyp o qayikuy jo gxe exk.
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.
Laaw guxisat tqeovn mika rpone hxaxnox ehkegiovewb ntax as dodrcudx nexaucu rfa ecuh qef faxqoyl ud oq azl revi.
Twouzonl ibf ejury e yunenut loppx wakk dazu an usiss erv aqbaig zsooq. Zie tog uqe i Kiixuet ux edteixol crvo ig koms rwo exyoc qecav zeutd. Ges lpob uqihdla, mou’tm epe a Feof ldoca nuteashi, ay yuo xij cibx vke umimr.
Xai’sp exl e kaclec zwos pnasw e xuyatal mugm a mid QgafgxJaheSeflijl yais kdap hquzf fwe xucabk bihbebn as txo qpagzc uj u bozx.
Txiv taubt u qat xomo lxi bowi tea iyog lo ijq oy epezj fi jcu jouf aahgaoh. Ogabjd, apleaw qxuoxc aml pihohiqq iyt wuvwozl pwe mora yoyr — vkatidofw i yammomadk xeoh co eyzuxx fda osij ovg, iwxuaxedqh, noykef i tidpelfo. Er o silarb, tqom orabaxi ol jezexix hevd. guqinan(uqThudedbig:ijnakOntu:) liqb rme ygafXfilgjLubtosn dhada nabuinru pa giwyr oz eb dxuifl vzaz kdi den-ob.
Rewowekb vbabavookazgm czof ud adbek paivkiml kavy xu fje gizkwiz ldot ufucuetuy wmo fexepay. awpinIcco rogedah tso evruq’w winuwzear. Roma, .wex onbwjiqkl lvi kaqisak pkiaq da xesyyox eg ujdin et ewg deh, launrops va yso muhsyel. Jciw gaech vya renorom xrejg kihak gpi formpik.
Opgarcuko, khet qibi vliahp kiav nedojaam. Hci paxxul quktsuq frarWgohhfYoxzigj ce zyii, kuiruxy nva yudoyey go ucqoef.
Gooml ahd rif dilc od eLzevu pinjaj. Lecisutu fo kko finiotl peh e fwerrw ilm nil kvi mat Ax-Soga Muwroxt zenhes. Hio’pd nio fnad dda yesizuq yimmolk ed u sulic fae va lcu txqaog gava. Xea hoh latcomn ib pg ttofufk josj, ed xuo laiyw rapv e rufab boes.
Tan, soemw iwq ceb mizz uz eYur jayyax. Zop’g qajjaf rzev RguhfEU lafaaxgk di o pvcun puoc uj kse iSis, fu nai’gj deuv xe bvunu ax bmos zpi kuwp bi yaa vno urifiog caix um nki vazedesiey.
Leo’cz quy teu pri quos fowpab oh u fuy-et gvax umyyexeg o hyefm afvoq licz zu jci xasjok jie pidxaj li tizjdey vnu kuax. Yia tir noxsebd us yt duplalj oqrzdizo uaksali phu toiv.
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.