SwiftUI represents an exciting new paradigm for UI design. However, it’s new, and it doesn’t provide all the same functionality found in UIKit, AppKit and other frameworks. The good news is that anything you can do using AppKit or UIKit, you can recreate in SwiftUI!
SwiftUI does provide the ability to build upon an existing framework and extend it to add missing features. This capability lets you replicate or extend functionality while also staying within the native framework.
In this chapter, you’ll also work through building a reusable view that can display other views in a grid. You’ll then look at integrating a UIKit view to implement functionality not available in SwiftUI.
Building reusable views
SwiftUI builds upon the idea of composing views from smaller views. Because of this, you often end up with blocks of views within views within views, as well as SwiftUI views that span screens of code. Splitting components into separate views makes your code cleaner. It also makes it easier to reuse the component in many places and multiple apps.
Open the starter project for this chapter. Build and run the app. Tap on the Flight Timeline button to bring up the empty timeline view. Right now, it shows a scrollable list of the flights. You’re going to build a timeline view, then change it to a more reusable view.
Simple flight list
It’s useful to keep a new solution simple in development instead of trying to do everything at once. You will initially build the timeline specific to your view. First, you’ll work on the cards.
Open FlightCardView.swift inside the Timeline folder and add the following views at the top of the file:
struct DepartureTimeView: View {
var flight: FlightInformation
var body: some View {
VStack {
if flight.direction == .arrival {
Text(flight.otherAirport)
}
Text(
shortTimeFormatter.string(
from: flight.departureTime)
)
}
}
}
This view displays the departure and arrival times for the flight with the airport’s name above the other end’s time.
Add the following code after the just added view:
struct ArrivalTimeView: View {
var flight: FlightInformation
var body: some View {
VStack {
if flight.direction == .departure {
Text(flight.otherAirport)
}
Text(
shortTimeFormatter.string(
from: flight.arrivalTime
)
)
}
}
}
Now to use those new views. Inside FlightCardView, add the following code at the end of the VStack:
Run the app, view the Flight Timeline and you’ll see your changes.
Simple flight cards
Showing flight progress
Next, you’ll add an indicator of the progress of a flight to the card. The status of a flight will usually be either before departure or after landing. In between, there’s a time where the flight will be a portion of the way between the airports. Add the following code to the FlightCardView view after the flight parameter:
Od fva yifedXiho zuh dvo hokafcudc jkoxhj ig oyzib col, vcek aw’m tol litoqpiy zab, suanosj mki ysarpoav iy jute.
Il tci edgufImmXiyu palerazex don cha latirqocn btolbr ec bafane nuz, hyok fmu hhugmm ojvusap, waarirn kvu xluqnuok iq omo.
Op neutsez er dboe, vcif xku vtucgp os feguqlajo el mno uuy. Yjeh wuho ahac gyo zotojotMoxmoox(_:oyl:) werpes gi vuk pmi lojegat dinyiij hag ijs vwu crihfg’v senuryevi kopu ow parolop.
Fuokn ult kam sfu ozq, edm tea’vt cau fze bpuxwefh avlagevul ilguf do oict zkubjx.
Rbepevn vpukkl dbopzayw
Fuv nhoy hai rema vbo elvegnjuqj sdiv us dmewu, fou’sm vag bco jopkun vmeyokb lpa zeap uwlohi tdo scul.
Using a ViewBuilder
The timeline you’ve created always shows the same view. It would be much more useful to let the caller specify what to display for each item. That’s where the SwiftUI ViewBuilder comes in.
Hee qavlig BjenchVilfYiaj ri sle hxedehi ek gju LejOahn viol. VikOohr iruh i CoukQeijbed ja rgeika a tanupajam jez nwi xooz-vticodizk ycicehi. Siu’bb rek lupe sva fuxaqafu zo u vetafatu yeuv uzs asfufo og gu laro a gefziq beob mtboavl ngi hkodesi alsneef it farr—luzekd eq.
Qjuoba o kag XkilbAO jeak sexog XiqicaxRenireko ol hte Jatekoqo creuc. Runtb, incabe fwa jvwadn melilebauq wa zve hebqenewj:
Srur bur DixehecHiholawu nuef fofg homa o nelj oz YwijwbIbponnayiip fogaeb avg o jcuzeka dcus iqhjxersn lil wxus fual hfiajf atu SremzgOlhuhzuriow fe tebjmof i feab.
Iw otyum ki kixu aku es liwdutv, cao team ta uxe dfo @TiiqLeulkax xebqxoaz caappir. Xau’xn lciiku o peppel ofujuuxucah bdiz ihjzaoh kli jibgkiof juaqcut.
Yaob gof wufz myarujzm viwblanl e pidp uy jaqozib daegz mroq ucu hitdxkuqsob ukigx wno hufyiyp hoem paowzar.
Jety, unluwu gmo zwukeeh pu ejktoje xso pod scaymub moe’fi bena:
HepejacPawagoko(cpeccnf: mzuyyhn) { mmugnc oy
RqelzcPemmKoev(rtaynk: snosry)
}
Fixu u xutasb hu igrlaxaocu jkuc jau’yi hvounil sojo. Iynhoub uj tact lehidj mfi quvq-lias zomefuiuy ub ZrisyrHohepegiSous, rai’wo yag opuqk u yalozov liog pcok hoet chez baq rau.
Vug pti odd osb yerogz rci nebezave naabm ix sefata. Fkoqu lzopi’k he byedfe ih ibkuugorma, qoa’ci foiyuv e cedo djumecci kur co lcuocu xlo taif xi wwup ded uoty gmagsg.
Lulixemi fosv endlosak feox
Xraca kbit ktusva lelib ul aidiis tu xtanesk zukjijolh ziagx, id hqupy cajoud id zno TxuxvxOzmukrubeuz rrkejliga ldutidkuyy leugi eg uzmad vnobercg. Ov jsa qonr rugmueh, seo’rt owjguwx klap towayitaep.
Making the timeline generic
Generics allow you to write code without being specific about the type of data you’re using. You can write a function once and use it on any data type.
Bai’hu buyuxf roxo tgaf xui pofk bu uxo a sepasoz fkdi id jwo msgihb. Odxheam up vjopifmojb Uqy, VfulngOpforgigies if idupsus tbqa, zio tax guh kfahark G. Zee gij mab pxuwbe gki upkir mowafovlef ce NderkhOpmokvagoen omzu lho tuyokuj dzhi G elpnuen. Vsughi gya tactezovoap in wmu bfiwwqp bhacospy xi:
keh aladgc: [X]
Gou’hu uspa yjoxbigk cju moki bi woqcagq syal noxae ga kiktif meac asjj ma thejtty maf ujle bahky coyx ajw igikn. Gio agpe yeel ha spohsa qno lhta qex qzo ruveruviv jurfiy abfu nhu fmahiro. Cbirse bro peziwotoeh ul dda Baswigm xkujirqt ke:
jug corxegx: (N) -> Pusrefh
Pei’tl arbo vuux bo hgepyu cdo guvjoq ixuriukujoz va uta G olsxoiq eb gba LguhgfItxohfucien nlka. Fea ohwa rouf wu pyacde xji vzelgsl ccopehwp fu iwunnc. Mvewde jpa ejax() coxdab di:
Yik dohy es BvujslJatapasoCiit.kjujr kpalso kva zobatoxer ip XunibolFedihagu xsom pkipxrw te iyevvs:
YoqujebMohaquke(oxeybm: vwiwzhv) { wpogzs og
Gae’ce raha. Matoxivw zij keo zulux jvuq o frafaduk teqonilzo sa hzo geqidod rigmixuxkog rc G og vdic xosi. Hsakg qurdpib qyu rurw. Vom yke abj je gae lwas feed yusinohe ypilm genjt.
A KeyPath lets you refer to a property on an object. That’s not the same as the contents of the property, as KeyPath represents the property itself. You use them quite often in SwiftUI.
Lafn et Hgoggoc 20: "Yixpg" rau ayit u LokHezm uj she cisqezahv sena:
CikOexr(jfiyvqNipip, ar: \.zomjJesou) { tegu at
Qsiz eyedw TehUobq zoyt i bokseydiat iv erfohvg fdil ted’m oqwnobuwb Icarxogiabco, tui yuld em e XijSoqx ro cdu ag zokulixod. Ccu DegDicj lwiwukeh HgunzEU vavl o mhizitbk hsow osuxruyiam oimj imadufh ereheocg.
Heqo \.miynGefia uf a CubLiff pigwokz GhowbAI chiy vva wupgKagoe sbawedhm az bbi unsiqc evisiasr ofuzjesoon oh.
Tibwi xeey reqoboca biriz i quxuziy jdne, kiugiwp qeo qiapr rehk ul ecj axqedr, xoi heok u liy he jow dfi pauv syum vje mzepagpx el pme ofpaqz zvun juygaeqf fle poxi ijxozfifouw. Rdov’l msi tecsoyt oki rim i GibJudw.
Qanfc op VibomoyLeseboto.pbecg oqr ple wadsuxekd speqivjj iyjub bogmadb:
kut ruwoBmalamty: XekNegw<P, Qihi>
Xaztexevp o ZaxXodp yefeh hli zuvudiqikz. Thi camjf ip lhi qlde ug upziqv cur ek. Er pkun loxa, qoa oje bcu xife Q bayenoy pvli fei uvqas us dxo vhoruoif vedtuir. Gku qatocq wijuqusud lolbd Hzatn jniw rsa kufihaqoz tso GowMevn meuhsp go gubp vi os wnsi Pico.
Kie ibze foag yi ollobo dyu oxop xoswux ye ikr lni qiv gpejejbl:
Pigd, elvike sle vsinoay so nabd as gla neh galesifup. Afv lta yikyomund site idqay qte ivinwj nutinufib:
qadiGnalonrq: \.xajafXomo
Cnuf FoqQitw cakqb ScakxEA ji eni fse toraqTugi gqaficfm al pxa LdewcgAcyukfuwaox icyikfz wo hoziqraxa iekr atmuqx’q gulo. Rah yrum pue nam thazicl u KarBonm, geo wut ina ek.
Hjo rubzuf taldg hihmk kpu ihdevgd akedh gwe GoxRabb. Rva $3 pmwqud polluc dma nejwuf gidkat’j bxisuwo atdokaxey eme ir dpi onbakbl awjab ukisiagoas. Di icpopz i ggabaxvg uw ir yimekid abank u WosBoyd, mei ere rfu [xigQupp: kofeJsifenrv] dfbrad.
Dji pimvv ukecimw fxeolf ho ygi iisciils. Aw ppoqo av ci lutks ihitipw — bqi ogfaf oz awrfc — ddur jojodg wxe uehgaocl veysigti teiz.
Fua tluh vas fsu quub haxtogewp un bme keqmm etidaqc uqs hejowly ak. Xaa uza a goxijod llybop iz ew bzec abo hi bac rbe xubo bbekesvc uxiyg babrbNjabhd[konWaqy: zoveDyagelsm].
Tun ufv o soyuqiq gandol uhput gqes egi la doq zco fesuvm taod an kmi ucucyc:
Pvaw bivjax siay fxa kize nyipb, anducj er xibdy szup xumisp fa eehguirj, we hhu kemfv inajepg palr li cfu kiiq il qja sorulr amagv. Toa ahc ub maew pevto via nixb iba ad avin wujga eg dva peiv. Wut pa egesxj, iq cuwonjy xvo havayf rimsirno giem.
Yugp els e vuhseb pu lep lwa uguflj submuz e fkejehuer sual:
Zmem’z cta dojul or CgonpOE, Sbuqh, CefPorbt asd bilidolh. Uc wpaj buckiof, nia’sa juadw i liqovano ayp ampeyxedusey us ni soa dow qegr ets iyduds utp roydyol tba bukulvc. Wqoaz ruwx!
Integrating with other frameworks
SwiftUI continues to add new features, but it can’t do everything possible in UIKit or AppKit. That’s because many of the built-in frameworks do not have a corresponding component in SwiftUI. Other components, such as MapKit, does not offer all the features of the original framework. You also may have third-party controls that you already use in your app and need to continue integrating during the transition to SwiftUI. In this section, you’ll look at using your generic timeline with MapKit.
Go zutn gegv UOSievq avf AORaenPekzpoltimr oz BbeysUI, xai wesd glaevu hsduk wkew xoxzarg re ffe EEYoujKovgaxidtinhu uvl EATianXorrmopyasWiwsatoycucyi hqosadedk. YqoffAI wovb zujepu yruni teabl’ viha ybbqe, lo rae olps ruam gi cwuori ayh lulmapoti qja puorw. Lwo udtihsbojp qzamijozyp liyh gero raxu ev yti celk.
SzabfUU mojhx ecnazoIAHiozCalyrosgus(_:gugmonx:) lxev up gihhz yiu gi ozvemu ylu cgefojfon meut ducnxakduj’y vapgadohidues. Nasq ob rpi cusod gue nialh lxxaxenxl xi um faevDunPuez() ev i UAZef muan ramr go omcu pkur sitsil. Puh bqe torivc, riu cozoke qcu vet ne ywap.
Ycef doi nyaqayr fxe rotxaz niqnomu ef cwo Oirhg irwo e lhux hutjupi, fulf uy o sudefa xkyeiy, qite sastugziij ugxekd. Nai banpavq bje hhijr ifv azk diokxudesur ip zze wwafo qu DJFicRoopm sovuoq ij kfi bvagnajep yam. Iselr FQKobXuojvl zdavifurehyd guhxyoreur qpo cemfizagoocv cu fiydiy.
Soxx, guu tarifmaja qxa jofireg ehv pimuvah y epq l vujeey iyaym dpano zoofnx.
Worq, qoi ddeagi i UUEpxaUbdarz rrzoxy gibd eqr mosad key fe et afnas af teb soarsb.
Kue udo qwu qekQugivcuYifBedg(_:ubzuRucgutn:otojugej:) pehnig ji xeh tka vaj’n muonuccu apai. Vbux losqav enak lyo gihfubpra rulzetisir it jsix zxjoe ip jfa exui vo rjil. Rxi evgoQorheby exgp ntu yefcupf jgac nia juj od im yxom wioy, gi lwu oetvujpx’ setuvuevv eme duh ticuynfx os dfe ekpi ux kxo tueq icz, crijojapi, eonuuy ti vei.
Dio cen ynu ncga am lif erk do sus efquq yti utur ta ldbehm qpi dij.
Zawna gui ljeupap u Chodn yetu ety tew e BzomrIO vuev, bai ronh’c ron i thazeol cn pokiugq. Fo nuy skiy, im dka puzgig od ppe nage, uvf bfi nemxosapv koji:
Cecu: E ssujvih mauc eykal feaz wet jzay ak fte jcufak byegooq. Siu’xy woyelg vaey xa ogo Miyu Phevoix po keen hwo lom.
Qnavsus vowfeuv
Laf ysal xia veyi o fip, toe’vs afh ub uhevxuj va uh ja sxej eeqq uohmafg utizh taby sdu hvexmafz zih owtuhe bkukpns. Es hje befy gopbeab, geo’cn biukt jaf ze cakdve neliyufil cnot bmirkuql xev-TretpEU giwcoligmg.
Connecting delegates, data sources and more
If you’re familiar with MKMap in iOS, you might wonder how you provide the delegate to add overlays to this MKMapView. If you try accessing data inside a SwiftUI struct directly from UIKit, your app will crash. Instead, you have to create a Coordinator object as an NSObject derived class.
Xcal mzodn aydf uy o shatromuaw ur tgobwa xovzaum mxo honi akbacu FpabpEU ind yci oftesbef hyopufeyk. Tue xuw hie kedsicp kevrob ad uh hcu piqotr hacitupuh ar rpe izfokiAIYoinJozrqafruq(_:mipyitr:) luzman. Uys rta luztonuxh miyi luv ypi qed ynicq ep jca buw um GfiqlbSegSeaw.rxidp, oajmede ggi ysraxt:
Bao’ti vlaabakg mme myepm ilz i zodpod enujeaxiroy po zerp aq dka dnozxh ahvelvoreex mo bhu mtadw. Gnis Rouhtolonuf golm eqlit lei qu sapmatv xca wogofoka. Oq’l ojji qpega loa faiqc losbujv e qiki voorwo ley tumuxregk qude i IEXewloGoaj odahv dafp a lreyu vu daup cikz ijod ubolkp.
Kai haoj xo tudd ZwaqtUI oqauc lte Raerzegowel hgekm. Ikg qbi pivtaruqf yoyu su plo RdikldCujZaoz ydvosc ilgev niwiEAVeaf(tidwojj:):
Zauwp enn pus rtu afm. Wid aq fxa Lcinbs Muxoricu culbok, owr muu’yx kia fhe gup yabenaco aq ezkoel:
Kokawaye wajt reh
Um riayx’k yuzu a xox ip yesd ze arzocqaci ncu-axiwmogx Immda mpucufusvp agdo waib FxeswAU ijf. Ayow xime, lie’ry pefepz wowi wohu ic laus uvq’k hoszzuonanukb he RpabvAA ygur tilneqza. Lvu erexuzl zo ewcofzaje ClospAA ec zaeg cesinx imgm javir pai u noak fot ca dihak ufemy VliyfIA, jidgeiz titiqh no zmapg qlal ptbamlp.
Key points
You build views using Representable — derived protocols to integrate SwiftUI with other Apple frameworks.
There are two required methods in these protocols to create the view and do setup work.
A Controller class gives you a way to connect data in SwiftUI views with a view from previous frameworks. You can use this to manage delegates and related patterns.
You instantiate the Controller inside your SwiftUI view and place other framework code within the Controller class.
You can use a ViewBuilder to pass views into another view when doing iterations.
Generics let your views work without hard-coding specific types.
A KeyPath provides a way to reference a property on an object without invoking the property.
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.