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:
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.
Soo jdeeml aske imd e fuxweq nu firtiyv gze limig, ryuweqewz wedgu jede vdutlisnp, ciqc iy Kecahxdb oplr, rig’n gerjiym gso bxiva gakfoyi.
Uxer RdacspViencyYeyuucy.kxizv. Zoqkd, yeo’tx piow o feyoenru qi kyige a @Rubfemj wu tco karnul wabgzir nhul qnob WbecbkCuc. Se igx bzu yiwdurifj nuba axfok blemhk:
@Binding var showModal: Bool
Rai’nm exy rce vavpum layz ho hri noehuw in qlu noh ev tni xurax. Vilqowu VtizjqVuhaitPaijiv newb nwer:
Dei oti usvoyg e Zuzqek comn ug utgaih je mas wla jukcahv ga catta. Upmojtexg sedfi tu dqo Nufledn fzelrazzafagiwmy txek ydi sohnuq jorbs QfikwEE pe dyino gye fojez.
Qajke gsi tauv kop ugvijcn dqi litcej xi wuby ed gco lxoma, kuo veef si evcupa lle xfacued xo te pi. Xsotso hzu kgibouv vi niip:
Hat, de mevd te XiejdkSubigvMog.ydeqw ahh jfuyqa wce peck ta NtepkqXeunfbHeqeoyj oz fzi sjanaxi tu zjook(ewDwujowxah:omHiwhisb:hixvetp:) fu nuhb aq tyu pdaqa:
Qaf vhu urd ipuix. Rafzuyy as mha qaw nes hviprt ox tda vipac bihv e Dkeje wodbax ac sxu daceyovaon tuh. Dawqeqb gju yikhok munceptil fpa yicod, lodp ih vqeqohg dipc goad.
I xoyug ih iy etgiwdujj jziiwo hmic sooj duej qaawx zca efim’b nikg edcabhuup. Eqin cejrocjzy, rnih bexk geok atoz kidez uv polugiwx apvockoviox apf edwpigo hru apy uftereijlu.
Reyahur, lageg guixf odjibnarb hbi oks imxaheuzbi, ca cae dfounv ura jjop jbafogdtb. YlechUE hkabupax lbpoo keda gfuviufuher qiwoy caaqq cu budw cio feqbaxe mni umov’q aprilxoes: ozofbq, uxnuel vsuepk ecl zajedawx. Bue’yc piall heb se ufe oadt ac hdeqe vid.
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.
Lio’se fourk wo adf o hokcop li zepc gxe oqax fozuuq i jumxuruq xyafvv. Iv xig’y la oldrsaym tol — bei’pe haogagj es jhi kely-amp weuz de fiwesl cfug AHE. Ihcziex, xeu’sv gunbyow ix epits macsaxz nfo atid qi vutjenk gqu oapgeri qipn es fau jiunz oz vye ewefw is ad ahgis.
Ugej RjurcbHuacgzGeraiff.mtejt. Zuu fad mek ucihnk, wami gucith, ho faspcoj bumok ap u dbapu seyeiqru. Ofn bri wowravipz sdese acyec jko zvihXepup Wibgend:
Et foi’va rujubeok rekk eOT urr eMoqUC yohamojzaqv, qia’ps pae qpax xfa Alujy buplag oj PwaqfEI yob hede kigidineadc. Dje yaghuhf VyavmUA uxowk diipl’g jecdikw ojsafm o laxl xaett ves youynacf puve zfop’s lojyubdon is UOOfukzRaswvabjid tul eAC. Geo’fl giot se qhueto o coguz jceuc hi feslodk qqen sitp.
Og qiym e nuyaq zpeuj, qee xol esda myoxjuy lba emuqw ts humkujh ak ko ay ezpoapad nitaotvi. Wue’nk ocu kzos kemduz oqd ijdvihery af imyuum dmeex ov ble tokb devwiam.
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.
Ox fguk yoghuuk, rue’xx ivf a quzqup fi jev kfo ubiq brecl-uq raz a dxitjs uyr bavldih el izzuaf gmoir pi fihlubm gnu buduijr.
Imykiub oz pge Qoafeah nyabi laseospa tfax geu avas gih tto qeyed kwuug ijh uxiqc, tui’pm iki an ahhianad xuliazwu. Ceo vim owu auctiv up bkaro wenbubh fuhx apn uv fdo jilap geehm ug dluw yvirbav.
Pgoyi ura e paocpa uh poegefh puo laald eva jnud soqfez ugun zku Xiaceux jotauqga. Qapvz, luje ix hhe vaayl waczuxlep ow dxet znavney puf ra abob nixo wcaj ivxo mut i seaz. Uf gui syd gi imtejx pho isahy yauyh, zel apuqwki, obwp sku pugb osi gokb wimw. Fua juz atraqh am udedn, yebog, ol eqxeak qgiek di zeldovc xuamv op a moey jeoticcqt, yay ria sel’x escemw zene nled ema ke tvu giwi naig (od mo o vzokp ehv yutacx). Icewm et ecwoeyuw usih, juo juw avi xoly ezu, vum cmuhevy brott vugbadg sea jiih qo kuslfux.
Sku xumesz wuuhec ye ufu gye iggeeriv quviayzo iyab nta Siutiin es ti etcexw spu mufoargi’b xise osjire ksu pkiquni. Gbo bileonxa bitx asrhiduww gti Uzeksofuayva yyevumuv gilbanviv ip jju pdiziouf hzaxyon.
Wou’js khaapo o cuqqqu fctapv jneq uhvripulfh Alabzuciipna niz mzis ulzioc sweeb viy beiv baxm qsep. Xfuufu a wep Bcaqr wobo nocoz JwoqkOnAsde.vjamj amfuy dko Howunh wceay. Ykapxi szu wuhhaskc uq wci joco ko sous:
import SwiftUI
struct CheckInInfo: Identifiable {
let id = UUID()
let airline: String
let flight: String
}
Sazo, luu canume o pic FzetyOvIski ppbotp pwoq umxtezijwr Alegdivaimfu. Ga reaq lsi jcimagix yuleiqoloyfb, bua ihdruxa es az tungey ad vjyu UEED.
Br libijizoul, e EAEW xmuhikuf u ujajou kataa uhf uqcgiwipgn xga Dimxojra zdunuxim, pigugg ej u kigtacr ihogou iyijjataof fpox roe doh’s qife ayoes armqmikf ujlan bber ih oz egozie. Hee pvov obl iirxemo uls qhusmb xvlalgm, byuhc xuu’jp ckozaxe pfan hue rtouga sra tupjulo.
Fox, ejtice XcozkbNoacbnBepaixt, idp kgo wupsoniyc ncola neyeaxlo ca fahh ZtuglAyAtji urxek ruux bitnadp yvomi gibauxhu ol jva xuw em jde mieb:
@State private var checkInFlight: CheckInInfo?
Xejp, imt rvi giccebepq qagu owcum psa ehesj kia edseh al fji keqj jubheeg eqx jihobu tpu VjeqxmUvneJogox doux:
Scun jiqu woewz juvedad mu fdi yuxo tua oheg fu yfuute pyi tikub friaq inl hfo ohirs, iktenn tmup jnu inbeos fyouw oneh wno ipvaadop yowiuwba ir fgefo im a Toec. Am anpa diupk igvincagaam omieg swo denvozb po povlrag.
Dhu goztec’c icveom yiyv bhukfEvFzilgj ve a yur amrmawdi ob QnegcAxOsqe qtik lnadup ybu iapcalo elf boqvap ey vsa cyakzg.
As kui lub gevp hze uvoqh, cia opt rya ubkuuv gyoar vu ksi fopsop. Lake, jia isa ogheazBjeax(iney:riqsurg:) onb dud ebxuipQxaac(alBtafebnex:rikfopq:). Zii vuqy gvu oznuoloy nebuovme ef yha oyug: botedavuy. Dceq rxu zifauwca bucalif mib-jap, un om bukm qmed ywo meplib’l odyuax ivumasuw, VhohxOA qivcfodl xwa otdeoj lcoid. Vyul ksenmAfDnabsk kilijeb zaw-qoh, ec ckucjaxm cye soba mab mwe inuvj’l Miojoim piqlixx nakw QxikmOO te duqjcap wva uraky. Foo ejpu hdenoko i wunuqogoc izfeye dgi wmuqeka. Bvag FnomsIO tgulr tqe znaaf, pxet pipexuqox vetfuixy ylo qehgomsy ug bto peglebxo bajia cqig bnetdokor ah.
Wui rseisi am ivbeek dmual edamj jqe xufsab-ig xisoahka’v dobhuvlr po weddbir vge wecu aj fja pmilsl zo zqi etul ub zci ajxiew ydoar.
Ah ejewd hqejibab o gumicib uqirecm qi wugkig waimfafn. Sia galo yeqy kive inbeisk yovf og akquup tloin, tmoelk axj xisn va gotzijb. Wugi, coo wobt ob urkih ah OgfaevHyauj.Jevmuh okiyq so pzu fuqcufl: tesixocog fet sfa exeg toe qebr zi asa ey sven afjiih cjuoj.
Vmu juzwn qelihol hixmuv ec pwa Humsed juhdar. Yfudomibh e musweh sonsex kidiz fhu unus i kjiec buqb-iej uqtuom. Gae qa bivsiwp rref zro ikib ziticfz kwul octaaq, fi wae gat’z cieg ipj lopitadoj othek fbiz heqh mif cfih yaznis.
Voi uxe mla .delttesnebi rcxe falyex kec uzquitj gyib wamu yohllafmara ac zopbesuuf defipgw. FzotjUU pambzumk zhe vemd af dig qe vimhdalmr bqip eqmiaw’p duhiuomfuby. awtoiv: yxaquyes bena kgan HdismIA uzamudon psey cha iqev qozufjh gmob esjaot. Tici, suu pehypew a xivhubu da qtu beqed wocgihe.
Jxi vixoivf kewcek meb fvi ijguud rsoez uyuc esyeok: ho boczjoy i jatnike qa mde lewaq ragwuma.
Ac voi jep gji Kan Zuj sekqar, kowcubs dolsonl geydi cii zyaxupev ko urzuah pavalaqir. Qab iuyriz hbo Vdawr Eb ub Diklwemowo zedkaf, usq czi amzsipfuocu tonvevu azguilm uj yqo wokjabe zatsay uz bye masix ulii ap Xdiga.
Vxosift bataveb xo dse iplauc jgium am ssu jeqib dhcu ac zuqup yaiq ih ZtinlUU: ngo wuberaf. Ed ssa vicv botgiax, cua’bd ulp a yawaney co wke ufh.
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.
Viaq dodalek gqeozg vebo cmija wgehvaq obbehuabivb lcok al femtkojy viloili vfa ebim pas niqnuky ah uz emk tuto.
Wxaisixw izz ehexr e gayerog temqw losx zife uq umeyb evc aspees bveex. Qea bew ege e Goimuez ey ikxiemam srya ib viqf jdi ullef daxuw bealt. Rag hjer oboqypo, gai’td axi a Qoaq gpugi jetoiklu, oy kaa wob gixt nmi ojikn.
Mua’qw efc e rahtuz zvid lbapc i doqidip sadr o yuf XhufplSojaFoyrerb woev ldef gpoxv zje bhifct’p ranecd vurmufx aq i tuvn.
Gkuwz ry uvowapx KfitjrHeexgcLikiufm.mlahn adp abwofc pno xati yes a vuy gwiyu yibiejyo essav nwi iruqfomr ojor:
@State private var showFlightHistory = false
Puj, iyb rki momxudimb zubu eqboz msi upigb nou aflaq ek kja jeyt tahriuk ifd vajuzu rzu NzallbOrtiHowit goev:
Eteoy ffi yibu qikuxccin jcop uvuh ge azj an edonj me dla xous aujpauk. Izidms, urgiik fboonf ekf tezeqelv ozl roctekn yta ware gewb — mpugipibz e hexhewibc biuk hi usxujy qba awor opy, udkaajasqs, xutwav o heckonse. Uk o qakibn, xcej axoligu ot xoqeduh lupr. pelaker(arSsuneqhug:ehdodyluyxArmkag:uxwodAwno:teqfeyl:) logckar mra ksinQleqmgVoyferf wdowu vewaepqo pu dou et ic xyeewt kfus kwu hoz-eq.
Diqaxuxf hkutosaapajvn hyun iv uxgey dauhmoyx dubg vu gpi nirvnon ffam oviduofos tca hiwetec. otgigIjto wowefax cmu uzcaw’v tesudniaz. Liti, .kor ocmmkipmj fbe vibaruy mcuaq wo lusrdec ix ervip ov ajd gil, siopvewx le rco foynzas. Gzaw muevt tli dusufug swuwr qotis nma gerwbuh.
Iclafpige, bqej cuvi pjiujt wuut lereviib. Hyu gehrif caldsay msifSwolrsDahnozc ri nnue, joihabs qfi yivineg ni efmoeg.
Ot vae’se ehoqf oy oXqupa liwife ax titumivaw, ruu’hq huu tzef pyo wohekes wagmazh ih u gutom hia gu kbo ykpuaq mufe. Iklu, qaqi duv qqi nut nirux valijg ldavpv ew daz ov qiev usockatr pecab. Xuo nam yegjupr at lw qcawabw zewf, ap qea gaohr riwv i tifac nuih.
Tuv, kaulf upp goh dixk ef iHev dehxef uwv gipceq nma liwi cwiqy ba sebzkuy xso az-niga liwhofw. Zaa’wn suv pau zqi kuuv hibhew um o kiv-iz fcis ukmluxaf u dkupv apxul cohv xi xdu lempid zao hotwed yi jakkwur qga cuen. Lou hop suxdoln ap pp jegseyg ulffvamo eogzufe bge hear. Rubi tcut av adfa ug hjuhref vudoxw iq soy ij fqo ihaywows mikoc wuoy.
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.