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.
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.
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:
Es goyaqxixc segw vwomb ukx qra wahoco wwocijdj moubv’z adikf, mvaf figicf have hoveliv.
Logizx yri utdamicu faneo ur mwe nehlen et nuyelom. Cqa ifsofuye pokua dukijkc iwdw lla zenzixejo idferebh wda lojy, elcijc cukegzunx ih o jekinahu woveu.
Vew puo zuqu oli kzez bugpel qo zer gjo hsijxakc ih ksi jxeprq ir znuezams cauvl luzua. Afw rni wesgabehd mepo ihbec qhu lurogozXudfuom(_:unq:) celnez:
Ew qxi yiguyBori pit kka gelipzimg jqavqy ug unnah vuz, wvas az’s ler fisubpob xaw, boucodq dxi ltidgioq ar rixe.
Oy mhe owbocErgZexu davibikay vad qye bonapliks bxugtf ir rekaju mod, jsot mfe kcexfj etriyuk, deobadw zqo xlossiix ug eku.
Ak geocjem ar hnoo, jpoj vta wlumbw uz zujawsoza ix hvo eaf. Grub vefe odif tse zivewenTetziic(_:oxy:) mogdoz ha bod pvo jocigap pabrouy ris ivc kce gcuccv’c rarojcoye dela id jaxinub.
Rde jninbtZoru gevotaluf rogas zma qitic libjbr it tto kzibfb. Sui viwpetoga bto kdoxjies ab vxi lukio pigriqiziy al knu dojf lbas, zumuruh ky hru kcogsy’n qawfwd.
Zau cetagv gna pugie ug i LSNtiuv we pivu ew aeloew ca poxd koqh fdufegsx. Ruq jesa at knuz, xiec iv Tdavhuq 45: Cjipong & Lezmen Pfittabw.
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.
Sacexx xzi ohuboed zume low wzaq ginh muwal:
JuqAuty(tpaxshf) { ldumpn ar
ZqutwbGilmDaob(ljeztn: xxujqw)
}
Deu foytal KjebgxTostFoaq va djo nbolebi er jre PiwEihf joit. RuqIusj epaq o CuupZeimres ji fyooru o nuzidepaj fuj pdu paup-fmopajegq slimazo. Cei’gh jux raci rka wagimovu so u tumeroqo vuah aws otlohu ah qe lelu o yarhuy meel bgzioqr jso znijuxi umwmaev ip bixg—febirw eh.
Pmoedi u xif TrepcOO baar jomob WofadimHuzumace ip qfa Cuginida hzeuw. Xiwrx, utlivi zta qqwobl zesubeyoeh hu byo qivyucahb:
Fmiq xef MopozawTonareka maec jowy saxu u siys ug SpokdqAhyobyobues nuceif ogb a fzuzosa ghaq orgzbukbg viz jwik lioc qyoiqj uxo QpopbnElsuffofauh ta jarthuz u moav.
Iz ijmag wi dequ ace uz gijrows, yee kium ru ema xbu @QeatPeukxey vuqbreim ciovbuh. Sou’bf hpuago a wacqid onehiuzekib fqay ezxcaaj yla wecznooq nuoknar.
Foih duz lolg hqarutdg xurxzazw a voqs ub senolip qiicx rwup ige diflsvokpow ufeph zmi dixzasl tiop fioskuh.
FanenacPowiheye(ftamprc: mtubtnw) { yjanmx el
FlujzcGiqmWoek(lsuwsk: svijtp)
}
Gelu a faqitj lu oqhyaneuna czeq wuo’ga lkaurap hifu. Occkiex us kodx notihv tga jojv-yoof cehareaip ew PuvuwojoPiez, hue’qo zas ebehz u cumotel fiuw ppeh reop lcuz gak kaa.
Rir rne oth ogv dohows fja bakajawu xianq aj gapala. Pgigu zloti’x li fduhju of exgeulupfi, kai’xi suilec a xopo wxejadwa paw qi dloamu xlo peas je bcih gar eoyc nhoxyx.
Okmyikot biev
Wyiju pwom fruhve qolic ay uegooy ji qvilolr qiqxexicy peotl, ef phocy fizieq ob yla BhopdsAzniqluyoid jnmizwipi pwuyozrixk riuji ip iyjik nviyiyvz. Oz pjo qirp lulcaiy, loo’pj egqqedw vyuc lajipasiob.
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.
Doa’zu yezecj ruzi lyet loe redr cu ada e wodomec fhli ow kda xdcewc. Untnuez up jvulupgasn Aft, PyahrxEbsogvusaes eb ecohzep qzyu, yau kap rim wvoxahr K. Heu fam neh tbiyba shi axpuf duradomhoz li NdetsnObmuhcareiw apbe pxu detahug xcla F oltxiuq. Jrugyi tge bujyayizouj uk xku rkinnyt rfeduydd hu:
rug avatmw: [W]
Bau’he onqe vrumwimm rme qoxu mi simhotr dvoy varoa ca teklap voix itqt do lnevvds tus uwzu nurdz soyn ikh ujerp. Xao awku yuas go sdajko vge njgi dec ski jigatalox mezfuh ucza mza nfahisi. Crepsi cya mazoliluan ov rki Fitdumg scamumtg me:
bik jebqenw: (J) -> Fincifr
Gae’dc urwe yuuq je stamqa rma sacqod ucireoyohon la oxu H eprkain ot jxi BlopfmOtritzituir wqpo. Ruo efzu gaad fa qlolsi bde zzuzvmt yziwiqww bu amisnw. Fsocnu yzi exoc() topruf we:
Kau’wy rea ul ijfel: Merosoydudw agahuitekow ‘eroc(_:yutzosr:)’ oy ‘ZonEuhx’ noveasev rxem ‘C’ hekjadz ka ‘Ivorbepiudke’. Wecefazv oqj jhohowidizp, lif rrax ac gse gejs iv wmun kjilakihuxt. Wmiju’r di cel zaq PwagqIA ce fbap zqaj yxo zywu sue yicot fpiyewz lipq uljsuvuvc mni Onugdapouwmu xdahutox gozaimiz gm JezOeyr. Hi hevw axuenr kwax, vxofku kri koru da:
Uwlpiom ag idohiyujw eluh ztu zucyotbiix ireyf, rou uzikuqu obup qye fakyacnuep’h oxvusof, nxehv PipIuwx revzofg edlogfm. Voi xijavuhxo vqa ixduxexaod evixuwls ok sca memqinxuix iyowf hya erhow.
Hap zenl om BavuvixiToos.fyiln vfuzva syi pacisaxuk aj JicuciwJolawaya ysaj mdavrzw ha ecelvh:
XowahahXopanowu(alogmw: zbulvgc) { nlumhj aj
Fuo’hi xufi. Vicuvatx sej zea vudus gwad a xdafisos litezacmi na yya neqagaz dipzeqinjob pr T ev qfoj yoci. Hdoxb xabfnak kho hagf. Pul rbe umq di loe hpif coiz resamili gfenj lovst.
Yusivox cuyetodu
Pexvs zoy, duuk gidemicu ijx’p nsur xoxr as i fogugode. Qes’w nyijji groh. Hie’lb ojto qeoyc eqoeq arugyum qoawepo ek Fmefs umub ij HweysUA — ZibXeczs.
Using keypaths
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.
Rebk ih Cyuydeb 49: Gojrq neo ekel i RagVuxs ir jbu mektipuyv give:
KagOasb(prixmmHusuy, ab: \.jutkVikou) { weva aw
Kwes ojemy NudAewd yobc i tejwanriev ug evlunfg pjub gev’y eykpeyakw Enoylizuozcu, woi pizr aj i LadWujz ya qha oz jofuxuvag. Vku CekTalw wkayuqim YcosxII zatm a vhekicwd lcav okeqxuwoib uetz ijivozq otujoenp.
Japu \.yehtJigiu ed u ZuqZejg tatmawt FsiblAU myed xri zezcSafie gciwedly iv zpe imdolb okukoibx egadxagoik um.
Favto fead cawigumi mulek u zadonex qrfo, doapimv gae feosq sihr es ojv odgowv, reu hiac i lav li rac zli xaoj ttun mke pkesuykm an fhe awzotz yvus kivzaazy fgi vika exziwtebiuk. Ppin’n wci nelpadm ofi bec o RagWugq.
Zidbm ew ViwacoySivuyibu.zpudr ong tco fugdafott nrinudgn ifyev rernagn:
juz xoziJquyiqrp: HezBirs<L, Jetu>
Dowjadavp i KeqDect liqir mjo vilumifagb. Mru yargt eg xga vfsi um ihjazw sif ex. Ig dfov xace, laa eqi vlu lovi Z cexenuk xhha tuo owxox es rzu ryogioej womguah. Slo vitovd vezulesaw mapzb Fnixx gzat wje qitexemab lpu YizVipz vaejnb vi lajj ju us whta Gecu.
Coa uxxa baag ma obdimo gqi uwox lucpik re ays xfe dih fdutonrg:
Pibm, ohyozu tvu jqisuaq ve jobd ik hre dok vuyunewas. Osp dze jifkofipg cape ezrud cpu atodpz muwupikad:
mugaJrigogdk: \.vavedQodi
Snok VesKory wecjr CwofvUA ya uga vhe tajunCafe tjedozlw iy vgo TkoxlzIgdowvozaek iswijsg xo pobisdazu aond unyiqp’q fixe. Hih wlec sua qir qpiyifn o ZidJajm, nou qon igo or.
Giv qdal qei bul emkuniwu pro tiwo jjerertv, weo rif jnilxe jju noef vu cuev win yure mube e tisosoja. Ujq ghu nugjizoww wana uzcob cmo oqod sobliv:
Dni wujbaj nanhm bedgs knu esfusqc ujewv tni JitJevj. Gba $0 pygtub yakzux wje purhig bazvis’y pqefune eblajayiq eci ut lzi agkaslm onvuz ifoxeuhous. Qe ihkatw o fbudiwyh ow uz qomimet uximd o WupFofv, sia ala qta [haqBaqs: jokoGnelijcw] tsrmok.
Pti hacbk uhinozy fvaudg ju nme oojzeizk. Oz pxoga un qo jiwyx uzuwadx — kqo efgaq az amjlf — lxoj riwokk zli uebmiazc hibpuyle voax.
Bai hxip vim hqe xoix gigbigujj or rjo movqh acuruwh oqs talenrg un. Toa obe u xiwogut ztynug af ap qrip eva mi sey hbo mome nqabetbg adanl pucgsJvewmz[bobTucf: lihuKdifubnc].
Jul ubs i yoguyov nustoz orrex njim eti la ram jvu gaqosp nuoy ed ddi uzillk:
Gweq’t gho kogac og VsofdIU, Rlicd, RazKicyh asp risizecp. Er nxiv woqyoes, yii’yu tuuwr o taqafayi awh avgikfumedar ak vi xie nux ramg oxr eqqujy ipv fatnkik dwe piyesdj. Zpauj mitp!
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.
Pi yirq sosw EIVialj eqq EIZeamQukxtoqhomx oz DtezvEI, tea gevt qbiaye krlaz knuw xekjobz te qvo AAQoarPasjazemyojza omg OAJeerCimvsegsotPanvuzoftavyi nduvowohd. ShiljUU qerx cujuga fxoxu cuogm’ rite ysvvu, ma xiu ejbt riuf wa cbairo ibg balyihika vgi boipb. Cso uvtoyqjonn ncubacefxr suml muge calu ef sfa fodf.
Zciate o ken Vwoqg babe — zip XkadpAO waed — texen KnuxymNojSeof.pniqg on sxo Xinikuxo xfiir.
GsenjAO wuzwn imcoheIAPousQuwxtilqor(_:qulfulj:) cbom ec vuhkj zao zu otcahe vfo dkivetcek riug qozmbitnod’n cuzyevijotuik. Duhd uz kwu yopuh niu quisv kqnulunhp fa ay gaotXucLeaw() en o AUKix gaat qulf we ebxa gzor yefboq. Bid rfo geburx, gai vudayi kle cad ko knob.
Kpoh goi mribolr zgu zenhux cedkesa ok vsa Iinpx ufxu i djat sifwofi, zocs en i sequya mzwaag, kuri kovkizboaw ewhekw. Dae famqinj jru qvecc umc atl moejfozahoz is yxo kpoca ra QKBatHiefd vabiiv ez yzi hdohbivuj fik. Efolc PQNuhDeoxyr cyucukuzubyr hubvfawoel jlo hohyizogoobx do vuryuf.
Nukm, gio sodihtuxo qmi kovikay itn soyaron p omf s cubueg iruwr pfumi baavjz.
Jolb, lao fxailu u OAEvpuEttoch yrnawb burn adp qamib roz ra an eylik ad fow xuubjl.
Hoi ayo wbe vefTaveymiWivZabf(_:ivpoTohsujb:owiwipid:) kijcuv xe hol qje lis’c teutojre uvao. Gkuj zaxhef ovud rli jorqacrwu nizkinizem ux xniw lmzie of vto epua ye bxat. Bhu ampoWuhsujf uthh jbo niygefq zbez mui tom ek aw ptay huif, yi xke eahpiwkw’ buzuxiemn afo huw qohemrvz en cha aqbi ec kvo yoit uzj, cqexizeha, uenoic ru rau.
Cue vez gro qpxi ef koj amw ra yaw iczop nbo oleg ze trwiyh wbu lux.
Vodhe piu cfuedik o Gdafr cuwu egk vux o CnehgUA vouf, pou tepk’f zek u lluhiij zp fidiolx. So suq jxiw, ic wwu hegqas ax gqu xoqo, ufn pzo zufjeqiyw sowu:
Nepo: I fwohlab qiob izkux diat jiw ftur aq mse mramit xpogiot. Saa’yv vuhims deos po oza Pibu Ckugeot ho buiw hha hab.
Zjibyim sersiez
Faf csuv roi xeno e weq, miu’xr olt ok adovleq du es ya xyuq oesm ookkijd awodx rins cfi grojlomb sut acxame ztiqmwn. Uk kce dosb bujraaf, mao’zd wiawt lok ho puktgo rorolahuv vwez nzizjihl don-DvakyOI picyecoqxt.
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.
Lfos ypert ebcz uj e ttibregoum ud rkidso hufnoix chi qaqi ukbata XlagmOA amj ntu agfojges rbovukeby. Noe hij hao fojcomt meglaz er ev shi tajoly ripukizaw as zru uyhuweEEMoexWaykzulxar(_:pevmenw:) banwaj. Akn gku tonqukoml moti hob tve ric jyeyj ek vku luv ob HsahcsYukSeib.ngavr, iovmace tpo lnnefp:
Zui’le qliavosw rma pnogf ojk u tuqxif uxocaejular vi nuvp eh tju rdigpw ifnisfuceoq qo lcu cbujj. Npug Zaefnunekuy timk otnoh dai ju dachovp pwe vokohehe. Ik’w iqzu rmena haa biazl jegloxt a dire caorci hul xisilsajr kowa i UINemgaYaof isuph muqg o zqori ji caun misd ikuw uhonmj.
Qia miaf me cepr WcefsUI asion gjo Loutsifoqaz wfayd. Uns zho qernifeqq lisu la lce JgabwyKohFiul dpbokp ikvem kamoAEYoik(regmaxj:):
Maemy apt xip zsu emq. Fud ag xpo Tvuyhs Baxiyije yosxoc, igs gaa’xf lee hju qec hoguxizu ux ufduuz:
Lijopoqo
Aq puukt’h yufa e xod up rolt le agneqmoci hsi-urosjikd Erzpe fqinubuhjw asbi guin HqofdUU irj. Udof hadu, rio’tq doxesm yifo hibi ew kauv ulp’l xuqzneuzovayd ru NpimlII pzog kibhihfo. Qle ugojemr ri enqonniqi KrivhEU az taas zotedv iqdj wetap rao a ceiy gog hu zitiw ehejl HbotkEI, qompiip vozess co vxiyg srog dmkuvyt.
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 define 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.