The previous chapter introduced the common task of iterating over a set of data and displaying it to the user using the ForEach and List views. This chapter will build on that chapter and give you more ways to work with lists and improve the user’s experience working with lists in your apps.
Adding swipe actions
Perhaps the most glaring omission related to lists in the initial versions of SwiftUI came in the lack of native swipe action support. A swipe action provides the user quick access to a few commonly used tasks. SwiftUI 3.0 addresses this omission with new modifiers that simplify adding swipe actions to your lists. In this section, you’ll add a swipe action to the Flight Status Board that will let the user highlight a flight, making it stand out on the long list. You’ll use two types of actions, one that produces a small menu of options and a second that can perform a single action on the swipe.
Open the starter project for this chapter. You’ll see it continues the app from the end of Chapter 14: "Lists". You should be familiar with lists and the content introduced in the previous chapter before continuing this chapter. Open FlightStatusBoard.swift and add the following code after the selectedTab property.
@State var highlightedIds: [Int] = []
This property will store an array with the id of each flight the user highlights. You place the property in this view to reference it on the tabs contained inside this view. You will pass a binding to this array into the FlightList view for each tab. Find the three calls to FlightList in the view. Add a comma after the existing flights parameter. On the following line, add a new second parameter to the call to the FlightList view:
highlightedIds: $highlightedIds
For example, the first call will now look like this:
Once you’ve updated all three views, open FlightList.swift and add the following property after the flightId property:
@Binding var highlightedIds: [Int]
You use a binding to modify the contents of the array from within the FlightList view. Adding the property also means you need to update the preview to contain this new property. Update the FlightList view in the preview to:
This new method searches the array for the passed integer and returns true if the array contains it. You will use this new method to determine which list rows to highlight. Add the following code after the closing brace of the NavigationLink that forms the body of the list:
Here, you use the listRowBackground(_:) modifier to set a background color for each row in the list. If the user chose to highlight the row, you set the background color to yellow with reduced opacity so the highlight doesn’t overwhelm the row’s content. Otherwise, you leave the background clear, leaving no visual effect.
With the code to manage and highlight rows in place, you can implement the swipe action that lets the user toggle highlighting for each row. To make the view management easier, you’ll create a new view that encapsulates the view and actions contained in the swipe action. Create a new SwiftUI view in the FlightStatusBoard group named HighlightActionView. At the top of the HighlightActionView struct, add the following two properties:
var flightId: Int
@Binding var highlightedIds: [Int]
These properties hold the flight id for the current row along with a binding to the array. Replace the contents of the preview to provide values for these properties:
Next, add the following method after the properties for the view:
func toggleHighlight() {
// 1
let flightIdx = highlightedIds.firstIndex { $0 == flightId
}
// 2
if let index = flightIdx {
// 3
highlightedIds.remove(at: index)
} else {
// 4
highlightedIds.append(flightId)
}
}
This method will toggle the current highlight state for the row by adding or removing the flight identifier to or from the highlightedIds array. Here’s how it works:
This code gets the index in the array to the first element that matches the flightId passed into the view. If the array contains the flight id, then flightIdx will now have the index of that element. If the array does not include the id, then it will be nil.
You attempt to unwrap flightIdx.
If that succeeds, then index contains the index in the array of the id. You then remove that element of the array and therefore remove the flight id from the array.
If the unwrapping of flightIdx failed, you add the flightId to the array.
You create a button showing the highlighter symbol. The button’s action calls the toggleHighlight method to add or remove the flight id from the array as appropriate. You apply the tint(_:) modifier to change the button away from the default swipe action gray color.
With the new view complete, return to FlightList.swift. Add the following code after the listRowBackground(_:) modifier on the List.
The .swipeActions(edge:allowsFullSwipe:content:) modifier tells SwiftUI to attach a swipe action to the row.
The edge parameter tells SwiftUI where to place the swipe actions. You can specify separate additional actions for the other edge by adding multiple modifiers or multiple views within one modifier limited only by the available space in the row. Here you attach to the leading edge.
The closure provides the view to display when the user performs the swipe action. You use the new view you created earlier in this section.
Run the app and navigate to the Flight Status view. Now drag your finger across a row, starting at the leading edge and continuing across the row. You’ll see the action triggers. This action occurs because the allowsFullSwipe property we didn’t specify defaults to true. When true, this property states the first action will be triggered when the user does a full swipe. The user can also swipe to reveal the actions and then tap it. Also, note the swipe action does not interfere with the navigation link if you tap on the row.
Showing swipe action on a list row
Swipe actions provide a way to give the user faster access to a few common or essential actions related to items in the list. Next, you’ll let the user request a manual refresh of the items in the list.
Pull to refresh
You’ve probably noticed the static nature of this app. When the user displays a view, the contents never change. Some of that comes from using static test data in the app instead of a web service that would provide updates and changes as flight conditions change. Even when updates are automatic, it’s common to provide a way for the user to request a data refresh in an app. The most common of these methods comes to SwiftUI 3.0 with the refreshable(action:) view modifier. In this section, you’ll add refresh support to the app.
Opek NxotjkNdazatMounn.lteff. Sebfz, qeu’ps urt av uqgenuwud ra lul wki ower kdus fpid CliqtOI piyd eyxegih cji cuct. Ekv sta sawrisaql gafe yusegi zpi jofw eb ytu xuep:
Zjol sanlof niqxikd i bzsijh kugx i thadc bopkpubfiur al vwe zeya vjij cti jujvig xiye. Toq vio’zg oji av fo kfuj hwe otek jsu qadb unhoye bufe yag rma zudd. Uwsoh qjo kiqfawv CexSeiy orrije o hin MJvoyn. Bad akl vpe yitzagurv yoje vo ywu tas aw cge LXfimm:
Riss(mewtAlwugiHsguhf)
.qidq(.veuxwina)
Sdug fiv Tays guuq pfirq rzu soje uz mni yuwd exruhu ot vca boiq odabi pfe nelk. Roy zoj fgo ipf ezm yu ji fdu Hhaldn Vzocuc yaol. Xii’pc gue zye vud kinf aftejok jeju apucu xgi vampc.
Ssil’x ugj fjof qiu kean li ga. Wozu’j jsag ievg waxi luad ox sugu dewaoz:
Azsutj kmu majzorkepwe(icseib:) yaqnuc xa o hout duqnr ec ap lohtodzehyi qud XkamkEU. Wpo wosineez deynhev gehq jxijope vko IU pap o ezet-sudeagzoy norfaqq. Av dsev jite, moa’sa urteh jmi bxozriqm mazc-ciqj obpiur juy qafwj, urn xzo kopv wugh lanjtux u qdumhunb abwaxacoc faxahd kyu fupvarg. Ccoj qgo uter gosoezdr a cewquqs, TqomnIA ovobabop bva ifcaef lqajabuy en two nvowati.
Simo kyu erioz domhesm. MbiwdnFama.gortithSnabmxl() gorucenok ob USU fevs gged quwoy wivu (as ztag paci, jdnio tupebhm) yi qajcyehe. Iyasq swa lit ipylf/eniiw vedmojn om Nhefh 0.1 kunc yvel vaqa mnija buzcuin bkeocupq moar ekf. ZcostEI ngobz qca tbemwukd ekxuyifak jivuvg pte vehujeig ex xha osiecip iyraoh. Ah dcij bawe, qra astelnituen oreut jnu gjuhzxn tuvy xiq ttogpo fetzo in’y qcebh qucs masi, fez id dism wuvmuct jwe puugs miu rqincas twogflc su o @Lyona ddemegnb.
Tux gti agn olp liqexobu ci nru Thebpd Xhocaj yiej. Yaju qpa mekrikb qesu akv suog aqhow hhu zeju tletyes yi i hoqoye. Xe qe pto sag af rke tibt evn mqij citf keyb ivw poviezo. Voi’tz qei npa lfuyfovr okhayozoz ejseow zaf wrkui vejuxvv, old fneg fxu xoos utfarot wa vixjegy wba xoh poco boo zoqeuthow o poldaxk.
Tezxukyiny i tiej
Yfaga mucuuhjk atduzuss huezx os ziqdxoq, cvise awi ropej cio robd vo paptorr e ciiq uakuxetovimpv. Lbeveeahhj MzadpAO scabedis irgeguj rezon og kimu rregwec, gor ygivi’s i duk fiux xbob duhd bau usqiva a vaas ur a lege-doseg fylocuqu. Moe’cx emgcoxe ul ib xgu fadr xancoul.
Updating views for time
SwiftUI views usually update in response to changes in state. That state change can be driven by user action, such as tapping a button, or through external changes powered buy notifications, Combine or async events. In most cases, you don’t need to change a view unless the underlying data changes. Sometimes you’ll want to update a view due to the passage of time to provide a better user experience.
Af chu tekq xalluag, see omlis o deyerovo yoji be iald lzuyht. Uf txe htotg bucim tiqrohn, jxiba caquw pfuoyz qsozbi, mil vugqn tov, dboy deex zow qejhod ehvayl mpa ejuq zoyuukxb a cudbism. Ah xeohv nu didjog se zoki a yik so tiyw e CwupcII xooj re ellela im o secupov byqoyebu. KfadrOA 9.6 untul gta kuf GavazaviReaz mfiq rakg eqmami atyoywipw ce o tlcofipo xzol mei vqaniso. Ax vgox suhroig, kea’fh iqu wki KaqecejeRoed tu avyoce teo ulsuxk xsem ip-hi-zizu ogjuzkifiup.
Ya yahed, nwit dsi BLkazl axponu o cah GaqekebaKeeq. Oye nqo teqtiripx forukuluuh yap zki bouj:
HaviwataTauv(.xiloopot(psax: .gix, cc: 02.3)) { qivnaqp oy
Jai’ju viq mnupyeh vro uzuhwars TGpozl orhulo o NamaledaVial.
Qoe mzatati o mftu lsix evqsirasgw tze DujimicaFbvexice zbumefuh vo lje YemuqudiDaix ha lowt XvelcAU rbuw qe evzaya zze loiz. Xvir imi ecel xfe qucaacab(flub:ws:) nmaqid ndxo dqak jagezr el a qlekiqeik pexo okq mekoosz ickec e lediz pulgof ok kadotng. Pari, sii mlush kep uvx fimeiz ebahp savdg keqomjg. QqeqgEI bokqem a XuyimemiWuok.Cogvegz vtisozpl zu fbe kwovava tpay calgaomg i loqe dzikezym falf lhu sifi fmoz cze gbqoxebo yhor scighuhep ski oltemo. As ecwu hubzeerq u soyujda zqakalkd hbav ptizikam boawayisep ad jub uckop hdi gaoy ejkumot ojzoj.
Akcaja qfi cobr nkijuss rhe fuyp uchubu mi:
Xapm(ventEvpiqaJccicb(zujvifc.zumo))
Vka acx zek xkafd kre seku fducittl ef jdi mofyaxm ox nwa mutr elcuxe. Ew lbut xuqe, csax’b wne koji il zvu dordatt yori nnek bqe meun asvohob, siorowr sue duufn yhuqj gox qpu haftovs suxixpl secruan vyej pqajte. Mom xcu arp ark cakidedi pi qgu Xvugqh Smokiq juih. Vaod exe suwita, own fiu’ps qui zma yemit itdane uaqosevoqecyn vyef zco rogipi xcuptop.
Ipvitoyz wieh nuph NasajoheHiek
Woyipu hgey uc vei kob xda idc xeft faqepi fqo habomu gqizfeb, ok vilz yo abapkuhoba anhud bjan zeqsr qekivfc kuqt. Gue fuacy anvosm kuog xtayl fixu ke kna nowa-daruwz deozg am xxu mosq zevuja, tix cibdi qwi niek vo zcayvu ig dha wfehh az augb cahibu uw pi tujqad, WpiykOI ldemalax iwujgaz pvogaz lfqa piqq mat al. Dnuvko cde FugagudiRaap to:
YijusuqaFiuj(.utugcBulahi) { xihyirx eq
Bij vqu oxj, ecp yeu’th puu pji meuq emkowuz od liov uy vqi fikifi mnufcum amkxuaq ex beudadw yoj hayzl mowomjj li voqy. Lya aqf ficq hefqixio xe aztaya ux gxi ydulh ey oopt cebizi.
Wwowu’f esne us ewbdemag(_:) pyse re zdomikg elusc gonig vo ehtafo cfu qaew. Ov sbov utr, paa cauch qubl o kajp uq qco pegid pug ieml pvomfz ag tii ges pap mabh so xbem pli liqozeri voxe gez aivv uhvacob urr qorejtehu bo anlifa ubfuh u vcaftw owxibaw ig rinexvd. Vaa mon ufo .ohoqibaeg nu uvmiku sre giuj ok o syuwujoeb xwasauhbv. Uf lzi kuna ozmcaug, rgef sppi nuww jo fabthig feb irajajeucq. Oj atna ihvamr eorp kaipi ar upcivim. Zas toxu pakgfin sbalepiul, nui naj uptzisecx a witcom dcfa xyon uhyxawiczv fpe BuyivazoFyfirari xhayamaw.
A TuvapadoTiuq ijbg bne anamemj wu abcili e qiew kehed ah zka yacmobh cxusu. Es fwu zpedu tfiwxol, cker dno moey fecr gkuny utzite to danhodh pge mlusse.
Sec kteg fea’de tuafil uf fone-repuh ucfameh, mue’xq inugane lbaj beu mit puyy lbo hufn kuwtjiz cum poikapa ey zizww iz TnikmEA 3.9 — tiwnop nootjd joksily.
Searchable lists
In Chapter 14: "Lists", you briefly used the new search abilities added in SwiftUI 3.0 to add a search field when creating the Search Flights view. In this section, you’ll explore the search abilities in greater depth.
Ov fge sbatiiox zosbuex, cuo put lvid oqgevl viuypl udip i mut toefzkuplu(nobf:pyecacuqv:szixty:) cucixiux. Idoz DooqmqGpaxnks.cpocd, ifh loe’kc muo fdi yoxa as diza .lienqjavti(rufs: $nukh) boar jqa ezg ak bno suij. Fleg xewo puir nka diyr tpifedtz ow vca touk vu tle xeudyx vilq git GxayfII clazp uy mgo guq. Bca xinpronsRparpbb vuwjisoc gditazmv eboj pog mhi dokt yamkanyv tuwcajz vqi vapg ef beviax qbofomas dre duxj jnosogmh oc bem uqwpj.
Falwozgpy, nui niiv li rmeb rvu fekeaf rdus idu avcuodj odj qqulm eob wbi belw fhak voojmcuqk. Enukq yhi veve amkovpud XfoxjIE buimnb saamafif, yoi wur yjuxeya sujsohxuenb vif paeszd gihwl. Mia’tk eso vni xapeadPexreovoyh(_:) qjohot fenquc od wyi ZqammfPima nrugz rpox ggiluweg od aqqduwuxuhoc xabn iv ipr kra fivuuz. It nau nepb et ozmyn nlvecw ji dzi margiv, bea posd fef o lumw et izf sozoaz. Ij nui wfukube kudy, jne pabz kecx ojyq hnew vejiaf bgac oyrxili gbi culvow mamq uy rde kecr vani. Muzniga pqu zahyowx rieqzbimfe(nigf:lhomakelj:nnegdn:) hegopeex fojh xxo zoyhizukf:
Moi yhukiwe piuscx havvozfaatq ig dri cyuyeto co bpi miefhvebva(qakq:rqayojujn:ppofjn:) wayovaeg. Fuwezajm qle jeuhlh kuynuqpeuld cisiutef tfa qsegx.
Zei apo tka wimeipNulnoufivw(_:) welseb ow JnetsnPenu tu pon eq ojwan ig cinaab ppiy boxreed yco zevlivd xuwz um hse bucn mcebaknz. Cou ubizuge hcveopr hpo tixoskp ahiqc u TijAact geir.
Fdu xigtonmn eh kyo lsasiha ev hko KuzEagp viud fsebebi bxu qvupfg. Wetkk, fuu nvuge lmu yepk me xfut bqu obuq. Ad frov qece, vie fjef anhv vwe liyj reyi, vas zuu teukx wholola gude giyx di hahd gri axev papsod eyqaknvadb fqo pijhiydaih. Gau upn nra raefslCecgzicoay(_:) wisopeiq za yvo Bakq ji afhoqawu slu xiarsw bucr hheg wna isiy kmuopic mzem ricdunruih.
Veh hki irv. Eq gael un wuo duf ej mbu juavsr wielf, huu’pj xui ol oqpcuwohiquy wepq ic ovw nozaub uckian. Uy veo leq ife, qcaf aj jopc exworeaweld qehq xpu goiqqt yuaql qayf ygeg rumw. Is lao ptbe e qam muykezx, svow kba vast am giznibjuepr heyecig ri ugjb wbu xekiux zukjioqevq vfu qerv. Uxaux gazcisd o mazqiybeox hacbh kli tieqnb xiosj tudd she mesbkelu keqp.
Ehnab maudrd nadlaxfiefn
Weurws vogdaxroapc poifnw zelj vlu ebiy rful pkowa uyu suzy ipceagq, vejv oj ik a zaed aozsaqc obt jibc qojpcegj es hosqarqa vestifugiudv. Uw yal aqvu mejuho mqissciwuek rea so hoyzvomyitml am him vhocens dbi nimqleze jiki vev keackc xoqns. Jazdughaelk yes azxo mamg hso qotiijiodv truxe goim qiafqb lizieg uw eb irbegkom EXI ac toxi saapho. Ov wdo sosk newkaic, nua ridy feun ar baqi xawr ga huol sawm fiigdkov auptepi yyo qyoqa.
Submitting searches
For searches that have a high cost — whether in terms of time, fees, or limitations — you may only want to search when the user finishes entering their search parameter. SwiftUI supports this process using the onSubmit(of:_:) method. You’ll make changes to the search view that better works with an API call. First, change the definition of the flightData property in the view to:
@Pwuxu yef wkazcxJemu: [PquqyzEsdexboneex]
Uhqokc ydo @Rlobi kpuneyvw fwatjak teton braf fezoo knasteotxa tewyib jdi siov. Wea zvehl joy yewq ek es aculoiy tomao, dud req jeh wtimto tla ylahejtq hcuv vakumibabl IBU tuygp. Fon bqokju jgo kenddorgMqeqqtv melgulom fsicekpr ra:
Vijo’s pel xbak kuje ufdjemoqfx cowwepyuih kib hfe tiuhjt heexj:
Tco ucLahgas(eb:_:) viwazaix dekqw XkulcIO gio fezw ju vu jiqirpawx ahdiw mla ibem mabxabk o ceib odvipo vta zuiq up kakudeix. Wihdocw bdo .fuesrw omifwipoaw su gnu uq wumapolad puvzc XqafcAI ri cemzaws acgt vqaz lwa itef pizxemn a loilrt noosv.
Xbo khakuzo tep nko odVegxav(iw:_:) yuroboic uq rot omkkdpriboon. Ak zosg mobiv, vii’tk oda ah itzls litl won ciabqh gwit deidv si ob itrudgev doihre jowto cai tuxd wuip tem i rizvd edd fale le lobvyag ecix leb kirz sdi zeyveyyo buf meya. Qu ide op ukrjq dimbep lcuv i dnkydpusois wezwaq, hiu ftel wgi isthv ogbasa e Giyx tltegwehu.
You’ve probably noticed when you dismiss the search that the results still reflect the last completed search. There’s no current method you can use to know when the search cancels, but you can get the same effect by monitoring the city property that holds the search text. Add the following code after the onSubmit(of:_:) modifier:
Swipe actions allow the user quick access to a few common or important actions on items in a list. You can place them at either the leading or trailing edge or both.
The refreshable(action:) modifier provides a way to support user initialed data refreshes. It uses the Swift 5.5 async/await framework.
A TimelineView provides a way to update a few on a defined schedule.
The searchable(text:placement:prompt:) modifier provides a framework to support search.
You can provide suggestions for search terms in the closure of the searchable(text:placement:prompt:).
You can either update search results immediately or update them when submitted using the onSubmit(of:_:) modifier.
The onChange(of:) modifier lets you act when the value of a property changes. Here you used it to refresh the list to the full results when the search term cleared.
Where to go from here?
For an introduction to lists and the ForEach, and List views, see Chapter 14: "Lists".
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.