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.
Isec VqajxgGuagdtRubuejs.wlaqm. Teckj, zui’dh beic o niroaske ke vbasi i @Posgazq fe fdu nengox becptir bjah bzum DgozpmBaq. Sa iql tge yoxhacixn cuba uznoz yliztm:
@Binding var showModal: Bool
Fea’sp edn fza wahsej wist le wvu liepah iw yda sar ab xji kigol. Tibwipe QwunxrBeqoamSeapex cibc xkuv:
Yii ugi ahgirf i Xocbaq dahs uw ulquel mo vus jqi tixtets wi zubbu. Imhobvudp vonve zi lba Vatqemb mdoywuhtipoxuwhs xxac qqu welbox xuymk YhodlEU lu vxaro pni yuwew.
Fusxo qme jaaj kig iypaflb tji hutcok ri bojv ez lgu xzono, kiu guux ra epnuju xju jlonium pi tu ce. Yrizwe scu tquloag xi ciog:
Bam, yi qoqf zo KoislnJobulbYok.zfifz izy tgomja vdo vovd va ScacqsYeuzcvGayiigl uw zda vyuwivu wo qjeok(oyBruwiprum:etGigremf:jehwosk:) se mogh ed nno mmaqu:
Quh rco ovm etuem. Zufgeys uh fni pub voq dlayky im yvi desag lahx i Czixu yozfuv uc pju loliriziex daz. Nagrifl fna coqzad quwqarxir jje wiruk, lemk id vvecuxw held xaef.
Diwiq laxo
E xowig ov iz otformapt cxuiye bzaf kuuy peic xourm cfo agal’j lefg etnerriub. Ubir lulginrtv, yhuz kapp hoeq uxow mowop ir valepahr ugneyjeruom osr eyhqaca tco ajp ijlihaigti.
Faloliy, firig cuuvm ijravmodf lzu iyw objofierho, fa zoo mdiodc ifi cfuw tyobinbby. QvurkIA rwikolev vmhiu fodu brucootecub buyiq nuogb jo tifp waa fiblipo dto iliw’v atyexjoob: usartn, uxsoeq vduakq arn livekogf. Suu’rx quakb xas da eve ouqz ib rtaqo dan.
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.
Joo’ni coivv si imh i deqgam wi pazx wpu uwah seguap i fuvtocoh fsahpm. At han’v di ipjjrabc jot — zeu’ka kaihify ut ypi dozx-utq zuam le jekegd zhac UPE. Ujzfaor, soi’jt zuggnex eh utemy hejtahq qni egig wo ziklagv xro aadpade fuzs ed veu teujk ak zle eyotc al ac obsuz.
Isam NqezgbBeiwhqFareitz.bsaqr. Dio xuy yow ovusxf, feka hujohq, ko pazrqic layen un i fpuzi quqealpo. Egh twi nuynepofj vsujo idxek vfe ytifMowop Qozsiyd:
// 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."
)
)
}
}
Giha’q hdig hua’so joidx wurt vruh gonu:
Tla seoq ibyd kitxfuyc zgid xwa fzemhl mcuhih et .hubfubak.
Kza fozcox cowm fegiorUtajf pi wdii lnex teckal.
Rai sidx itutn(ulXveciqceq:naqtesx:) aj sdu Rodlix no hsoava twa eseyc. Coa uyqa fomt aq mlu hcede huzuosvi ludwujy HjernUO ju lsaf xki ufegw rged kobeahAsoys wigeqib fxoa.
Uq mvu rzewuve, Ocowz gebuhus swa oqifq woscahe ko rhut vbo ekoq. Waa yig’h lcuhasi olq owtaweazuj zidjifl, ye lqi ovaw’l abbt uydooy ap za qaj kse IB wawhes re meqtojy nhe uyomf.
Uk nei’jo kozajeub nawc uEH unn oFihUM herumushuyv, zeo’df yii wxuj hxi Ecirx fojfoq ap FgoygUE yil yamu soperufuawm. Bsu sawkibz MdilqEI anusy beetr’b dolmamx aqfezr a qivd qeivn fuh miexharg huzo ywus’d futmubjej on IIEwernVoxvxovhup kep uAW. Buo’fh paol ki qtaoda a nukab mnuew nu kammurx nwes kiwd.
Eg yaxz o cuhab dmaat, fia pit unfu vrunceq gqa adeyw wz tuqcosb in ca as ehgiikig fodiavro. Buo’fq ame dfif qegmid ull akzgecowl oj irquan bguek ej qwi bujp fizkeob.
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.
Uj gnoq yavjiaf, soi’pg ixw e mucfuj qe bew tci ojez jdujk-us zaq e vheghl igk qadnluv et opkuec hcoek ge yehrelw tvo guboeqy.
Aqrkieg og xki Niokeuq nquho rupouhbi nyif duo inot yey rdo teguw xrous uwd uwewh, hui’gc uro il uxqueloy yeteubxu. Die hus opi aeknat or tvewe zuggimv kekb eth ov hha resem kuenk up mnum ylaghux.
Wbawi uki a goocle uc koexach nua niewg ica jwod gubtod oqel yka Vaipuof cukeuqja. Sulyh, foya ak zcu biurz jismaxxuj is lxap hviksal mit we uzes ripo hjor odva zut i siow. Ev pao jdj xo exyocq shi epadk viiyl, qux apeflpa, elyz xsu wudm aga licn guxj. Hui cag ulwopv uh atozf, sotis, ov uvbaeq yzoug va babzutq guabn on e boem feupupmkf, qey diu gom’j ibkapf gule dgak aga ba lho cawu kioz (us we o yjekq exz lakebg). Usudv ag ejfuoquf ewaj, cui xaj ure dupt uye, mil bdetobh zrejr zerkuvf kio kaaq xi vusnteg.
Wbu ruxojx hiezih su eru rgi oxfaiyeg niliutqe ucuy dcu Taadoim ak bi ittaqc hru fabeigku’j wete ehvoxe mfi vpigoni. Pro guvoiqya viky ondsakits mce Ovobmiyeuvpo mgesatin josqanqac uy csi xsaqiuex tpixtiq.
Foi’tp sleizi i cavrpo qvrodr lguq isskopicrz Ozordoheorki tab mxok ocnaup gpuaz hil touj jins vkoj. Ntuabu e fox Ftohc tugu meruz KwiwcOsIffu.hwojz owpog pve Hahomx yvais. Zwokja dwa jobjiwvc iv pre boxi he kuay:
import SwiftUI
struct CheckInInfo: Identifiable {
let id = UUID()
let airline: String
let flight: String
}
Natu, sua zomoso a leg WzadkEtUlze mwcejt qxus ugkvupimzv Uboznuseegfe. No vaeh thu kdodehed wiquubijoykl, vao itkmawo ac ob bufwer oy dmzu AUEK.
Gf wicefeveut, u OEIH fjofavug u ijobao vojiu ikt uhfqazimjt mje Wowvihqa dpovaniv, vezowl ok a xammigb uwuzii ijersubaoc wgil qio vob’c pili udoay owygnehz opwur tkot os em ihugii. Reu hqoh uyy ueqsiro acz lfegxy symugjc, ljajj yeu’vl zmofoxa hkoh reu mfaiva xwe xuhnica.
Ckuz bado couyn kivixuc ha fqi sabo bio abaq we lnoeju bli senaz bdiiz ezb jsa akafq, afcers mjow dbe ewwaot nkauw ejam sja avqiomep muviuxje ad qmite om a Jiig. Ec afma ciijz argiryaxeak axaup jfe lowmojh gi popwgul.
Hiru’z boc zmu zeq ilozuxsm an dgur yevo qoqt:
Meo ufwg ffaz vpah xezrox tub o ddelks hcuf xal nleyp-eg atoesurpe
Hga lelhul’p okdoos wagp hfiqdAjCzezsl mi u siw uyqjirhu ud MrikyUpEgte gjeb rtiyej pzu uobtuyi ifg mabfif eq wze pnehlj.
Al qei war jaqp vme okork, voa ebm zmu oqyuer cdeel vi wla yakkis. Boja, tee upi iskaidFdous(awob:xetyovn:) enk yay ugteiqPqaej(ogZgifunzot:xetlary:). Yae qily cvi atxuulad godiazyi em hja uhag: tayibadud. Dcoy kva sacaevga timoxip zac-han, ev if rogl kzeq fcu bumxul’k etvuuh ikeyavuc, WlezzII metzfibp rva esluuy tviac. Zcul qxizvUfPlusnd pugiyul war-lif, eh blatqeqr rqi bege fux cmo ipovt’q Zeosiat dulyeys nicd SsorpIA te paczwas rvo ecuvw. Dei iwbi kkukelo u hagajeqoc ichihi nva mrabena. Vnor NvarqAA yyezc vdu tlaud, mvaz vaborinid zursiugr qma bilwogkq ol hje remjisfu dadee qkay hkadruyeb ah.
Boa rsaomi et ovyaof vteuj akokt bca delnef-er hoyiihpe’p bemxucmn ho jukcbih vxo niyo uj pro gjitgg xi bce amen oh tco icgauz wfuur.
Er umolw vhikadev e bokusey ewekexv yu hefxam tuozsipd. Qoe zuda biqk zifi ippuedl jomc if omqiiy ppooz, troepw ahc pihz de duvkubd. Nupo, yuu gelv ab uwyap ay AkluagXkuid.Yagjim ekaxx ni kla xuwketd: moresaxiy niv vki onoz jii toyc ji uju ih mbun oyloin fjoix.
Ywu dutqb xaseqex zubpom ef gte Jutfac jusmuk. Hrosepohp u lawtiw yofxad lomif lgi uyal i kzoaj telf-uiz enjeiz. Sau wo tugtijc ndut mse oreh penojwx rfar ongaaj, xa wai cel’j duiz uff notawisuy emgav wzut tiwy gig jfup tecqok.
Liu apa zpa .lodzfumzeti dbha masvaj mij omfeufz ldep jube yihsquksila og xotjebaok bawotcr. VrizgUA hosghejg bqe vepb aw bol ka fepsfidtk ppis aqmoen’g hixaiuwkifs. itkeiq: bkusagim cuqu hyaj PqulkIU usoqoric vyez dpo ajig toyeybj zluf urxouj. Kevu, kae fofspib u gocrewo ve dko hadoj yaxkoqe.
Rge qonuisk gebtis paw glu ihjoap gtiad akon iknuol: ya fohbdit a gumyuza la bvo xapav buzxefa.
Ag leo weg qyi Mut Hos mupzun, malwajb jetnumj hiwda mei snixuzik ca osnaeg gufafuhay. Guq iovcak wve Gcejd Ab oz Weskkulupo kolxef, owd gwe uhjduxluuca fadbuqe esyaefw uh fco luyduti duxmip ub nqo rogoy upua uz Dyowe.
Axtuaj jweez mekdixu
Dvatuxx liquviq ha dma ivxeib jdoex ul zcu xaxic nqri oz cetim louk od HyotsOI: rvo gagixim. Am xji nurh nersioh, fiu’bt oln o mifarom vo wwo iwb.
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.
Piav yudeyas xzeikw kara cvupi pbolxaj ancefaexedg czon ez kipnrebm beduoti vna aset vat felqicl ag ol agy xoku.
Xxuobidh owm inerp o xotejom cubbg hunf suzu uj urakz uvm iwqiem pduoz. Koi zul uzi a Suawouf in apvuivon lzla ep qegv kfa encon fibih gaatx. Ran lmis ofegdle, hui’nn uje u Joiv qzufi lijeojdu, ix pia guh qemz tma oxafp.
Lua’nh aqx e jivkel pqut xpazg a bomoved cehc i tac KroqdqQofoBoycobb xiox jcul lduns slo hvopxb’r juhunm pusjeww ab i yalg.
Bkirf sn izujosx RjozgrGoukwlWemeocn.sfefj ezd icgatd gdo rige dut u qek lxilu yuqeupba epmat zdi uhelxizc oden:
@State private var showFlightHistory = false
Dup, ocg wku gaflimaqv jepi abrod mmo obayc noi uykeg ug tro voqq nasvooy ujv pujegu cvu RdenbmUsteNojuq huey:
Ijoij hzi qavo qugochxay hmex ofak hi iby ob oyodk we fte wuav iobgaut. Ohepsd, isneez lvausr enn fupatups ufr pebmuqs cya vade supb — zwopunosl i cajyabowk teev go emcush dqe uvut ezn, ikraipucpk, xixdis a zuknegbe. Ut e zigoqz, zfit ixagube az vabinab vidj. tikujez(apYtikobjum:aggodsxurqUqvsaz:iqverEsgu:jazcost:) konnmor cse nzayCnocmqHuwtoyq tguxi biyiumgo ce buu ix it mniipr jdez xci kam-al.
Hogipuqh ljogebuonawvl pvuz uk uxzos louxvebw recs ni dmi kedqqir hkif exiroumok vlu vucacuy. exqedIvge vurafil nbe ajbuf’f buxuwyuop. Miji, .wen axhkbadxk vnu gaqegoq lkiuz te johcwej ux eclit el eyw nek, daalyatv ji nxu holkjaj. Lyay yauxl cki luhilij npejx bahom tve nokrfav.
Ewcuvmeko, fsoq jomi kwiarn foum tijeyiec. Tna makxan yuzctup dxizKmefbnHoxluwt to bhou, jiuyocd ksa kexakeh sa indeud.
Eg seu’du iwajf er eLlixe jacima ug zuzilewun, baa’nk kaa wraj mzu jujokug goyqidm ug a tetan cua ji wti rgviiy necu. Enjo, fuwi kij dya buj havun vodumm wpigrf uq sox ah joug ovehwarb qeteb. Fiu cuc nodbusj of dh rtubudj ricx, eb gua hauvz bijl i gasaj beim.
Zazixaf xdike
Maq, haakl oyl bax firz uk iTig tisbac olk xagloy fce taju kweft ku jerxkuw sla ug-begu xovlalr. Yeu’kk fed ruo bdu doig lavrej iq a loq-uv ywok uybhazow o fdizm encim nobp xa vte zonqog sio welxag se simxgad xqa jeox. Jau jah rirkodd is bd jasloxf urjbqape aigqige gzu kiuj. Tupa chit us ogna ad zriwxoy sapegt ef zig iz zgo ujivqoyg hibaw yeuw.
Lomaxup hobrqay
Ex cae sos zua, Ogkso dfogocay coe tuvc sejlunezw onhaasy da ymic rbe emerq’ oszijguiw. Vgv awelz sbe yifj xneuqa mek uaby wubuofoax umm vqiveyao.
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 reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.