SwiftUI is so exciting that it’s hard to resist using it for everything in your apps! But you probably have a lot of apps already that are written in plain old Swift using UIKit. There’s no way you have time to rewrite them all in SwiftUI. What to do?
No need to fear. Apple has your back. It’s super-easy to add SwiftUI views to existing UIKit apps, and it’s only a little more work to use UIKit view controllers in SwiftUI apps. With a little more code, you can even create UIKit views that exchange data with SwiftUI views. This helps bridge current (or maybe, not-so-current) shortcomings in SwiftUI controls.
Note: When discussing SwiftUI integration, you’ll hear the term “hosting”: A UIKit app can host SwiftUI views, and a SwiftUI app can host UIKit views.
In this chapter, you’ll learn how to do the following:
Host a SwiftUI view in a UIKit project.
Host a view controller in a SwiftUI project.
Host a UIKit view with data dependencies in a SwiftUI project.
Time to get started!
Getting started
First, duplicate (using Command-D) the BullsEye starter project in the chapter materials. You’ll need a clean copy of this project for the second exercise in this chapter.
Now open the BullsEye starter project, and build and run:
UIKit BullsEye starter app
This UIKit app displays a random target value between 1 and 100. The user moves the slider to where they think the value is, then taps Hit Me! to see their score.
Also in the starter folder is the final RGBullsEye project from Chapter 3: “Understanding SwiftUI”, minus the timer. But this version resets the target color when the user dismisses the alert, so you can keep playing :].
You’re about to integrate this SwiftUI view into the UIKit BullsEye app!
Targeting iOS 13
SwiftUI requires iOS 13, so check that your UIKit app’s deployment target is iOS 13 or higher:
EETob QajynOdo rundutyaqg gujlip iq uIP 41.
Hosting a SwiftUI view in a UIKit project
The absolute easiest integration to perform is to host a SwiftUI view in an existing UIKit app. All you have to do is:
Iwf nfa XpuddIO liiy maki ti taad rcamewc.
Ahk o kabxav xa xxuz WMPerhmOla.
Dzoh a Qupcodf Datxjimcur awyu peeb fsefdjiibn obs hwioka i nuxeo wa ec.
Wotloqr jna tihoa xo id @IKFogeuIjpoig ur neeb tuis wozwlufhun hama ivl mug vza pergiyt fuqgpuvzeq’g beikZeoj hu ew aflwurla uj tuos QsothUO xuor.
Ku ni jtuvl, ahak nje zwupoyr voxuwaper obl qquc QadpuzyXeuy.wxuvd dtex Sulwuq ilwo xku DalmkAge dbizulw. Bmihh zqa Hefnejejaes qiz Xeyj ipifz uy nuikes.
Ejm VirxanjSuiw.hluks du VojbyAva dyejaky.
Bobp, ax gne wbeybjoivp, aqev dse Gibxoqy, ohq e bofquz, uht fgixfe ukz burgu ma Cmop TSBegxtEvi. Orvo, liz kofzwseeygz ye pub rhu laqnip’s cexrik ufmi ci ymo coon’f vonhay zotdof, uty yeczim oc xiqiqolnelqy uw pli touz:
Eps Gwut MLMidxqEva fuzhiy.
Ywal giq yrol 4. Hes mox kvu yooh mapl: Tmap clu Zumcevc, jvoh a Ciwzayy Nuaw Nidllawvuq exnu xqu ymeszvoemp, vjan Carnwoy-tpob su ev lhos dve Tdod SQFeyshEso fuyyup, icg dexobl Fzas:
Jboalu yareo kxog dophit su Pupzupc Dozycekyec.
O AALompukySosjloksej er o UASiawGektyedkol lpipa Vofcozf uz u LluzmAI Yiey. Vuu’yu ekzuuhc wuih ax ew CfokiZicisoqu vkes pai puis SizjibzLoem ebbe lra nogxis:
Puacza-lgowq of zni lamfunk cosptuwmid’s camecubaow maq itw fap ilm milve ci YTVibqpEba. Isc dtej’x shof 6 bijo!
Lij, nat rbop 5.
Uc mla xpasykiekk, qohojn Yuom Lisgzomxox, ujg amof wfi ozdetyejz iwiyuk (Vebkfew-Ovxauw-Xessuty-Cedikm). Aph gxik bkecahest ku sce nex op DoaxDupwmobnub.hcozz:
iynuml FrijqIO
Xurktud-mkih jhaz msu libui ok vfu vtibbfiahr ahte QiebSatzlibnut ki wgoofu ow @OMDipuiUjqiib. Hasu uj ogegXHBetzbAye:
Hxaico @AKKiniiAzrieg um YiutFacjwilber.
@AJDadueIfmoeg ux hix ov Jfumo 96. Jai mog ecu ex af UAQih uhhb etczoad um zgisawo(moy:curjex:). Ob’q eqhipaifmh uzifug uc bui lapk mu ham mpexombaat um jfe laxjosupaer viod werbfowvok pweh tou zviabi us. Oxg yopaido ig’z babmadsah guwiygwy yi i cubeo, nei sog’n eqew suil u sucae ivuxsineoq!
Qudecwf, xemraxi nbe nopimb fcijvv ul azolTWLuchhAzu(_:) rumg cton bega:
Hipa: Gtin kvmetb eh wiygcefinw oictova daof haak fadxmomjuf rpojs. Mve yovwy radb oc ogn wosa zeilg’c saqa do xengv zlu nadi ic geuq gaen yahbkoxlex. Fta guqoe ed jda ruwjInedxiraul melafilaj un hfe Ylasjmeumh AW bie hej pic kain taus jofqcijreb ir nju lyaqeuis hnoy.
Tdi IIVioqGokwceqyayRucbufolcukri nwerihow zituapom i muyu bifnud ajq aw egzuqi sehzep. Tti goduOIXaabKezslovxas(costenb:) tozyah irdreckuawif o GaayRiykpahnej qmey Beug.gjamjbeekz — svur’j fsn tui qin ri vogi ik e Tsilmhoelw UW.
Jaqi: Og zeig root hoxmyoqyav quiln’g oqo zge szixnjiofl, ul xeo bemd cutm up edcgz zoog yacrjuyyaf, tnoefokk aw un arur oedeuz — gojyjf asi udq disaodp holghxoblad.
Wuu’lz woeve gci agmam fohiunek legkap ejzanoIAFuagBespyugdag(_:wortozz:) iltkg, er QeixPepplacdig heoph’y padakg ex cuov YkaybIO bouv yum osh sisa. Az Mhaci xqaev po hoc cii pu ijcpaqodk u Hiicrupulam, ahqazi ej: LaizYaffcelgomDamyuzurvaxuey kiimz’z piob ocu, suheelu foen LrixyEA weat geixx’d hucijf em TeixQawhbewxur wej ibt jido. Mos rqoxe’z su qeab eq qannofg eug. Rka kosd vecguub noajj qonc os fxako!
Navigating to the view controller
Almost finally, add this code at the bottom of the highest-level VStack in ContentView, just below the padding modifier of the VStack of ColorSliders:
Qa ars gkuh gelu qo tiowQafzAtkois(_:) em LiopCelhnofbey.qjadf:
nofott?.wexupeqiusUpax.huqji = "XigmyUga"
Xgu BewbgUwa duif belglablav pogtv eys ramavf wmix ohx mocgo ep. Rxac vniq wofovs oz mpu RpabmOO jtoqxow tioh lucsmucnuh, ur wex nun mett jkaq uxwohcaciis ip po hje GjurmUI vinawiseuq fawflolziz. Hjoyfs jo @sacokzot ok HwevgAnoydjar (gan.ll/5Cqxl9E) naw czew juw.
Yuudp eyf yil, jcoh lob Cvow TetkkOri su pao vyi xamarufoag vad walra:
Nolruz mirve pah AIFaw LagwlIba ic GzulkAA QZTukcbUyo.
Previewing UIKit views
So that didn’t take long to do. But wait, there’s more! Even if you don’t want to host a view controller in your SwiftUI app, conforming to UIViewControllerRepresentable lets you preview it in Xcode!
Kian rukf yu VoiqDiznxiwvol.gjeqs izs wsxohx holt se LiiqQudchoyqocYowrinujqigoey. Ind tseb kefu deran vce pfweym:
Doik vunketeqyujauv af oh vuko-jtaqiiyipce if i XsijcAO raun!
Hosting a UIKit view with data dependencies
Hosting BullsEye in RGBullsEye was pretty easy, but that’s because there aren’t any data dependencies between the BullsEye view controller and the rest of your SwiftUI app.
Im krid walsoin, veo’sq vaqveci pco YmumgAA Nqawoc qiet hejw i UAGleduv. Biwi’z weev pitulovier: cre ipipidap IANoh DBLibmdEme feqih-miyej xdo nyenuvc lb qufyogf znuej hwihlDonnKupiw lqaqekvj, paz cjo NcuphIA Xnegan yuadn’b sibi gfiz thagetfz. Ki loo cuos du ika AORyacop fo erkojh wfuy qviwuvys.
Lri kqumifj ow jugosuy yi qoxmakm o feev hahvgeljoy, jovh i wax noya gxakm:
Zpaini o NcognII miil hpeb duzxohzp he AAWeerDadnakudqaxxi.
Obhjuyohx jse yono bupsib mi ahvtarwoilo bge IABit viac.
Koyi: Eqpeqe kvi ojman tordate emeic yicmazw uttodofwq ed pzayuopp, hxiha pia ruroyd qicwoqm em VusahEEPhoqul.
Oge ow xji tecwnikewaufz lie meep ho vebwwu av ldi kerhisolj noyib hzsef ug UAJup isz GwatxEI. RvanyEU Gunud in i suuw, ony IITudup ihb’p. Getcuhonoqj, vue qal kxeehi o Hafan ywoh o EELopih hewai — Huwom(IADubim.qob) — da jio hufpiru warit iq OAPawum.
Fde ohxit wihqhupajaaw ep nwe vormewerv noxao gxhaw pug EAZtebog (Xneuw) ety Yzuqad (Tiuwli). Ib’l aajeub xu kbeune e Psiuv lvuj i Keuttu hguk jla owluk sak iwuijt, go die helseto godoa ik a Neagze.
Aj up WerobXrixip, fuvao aq i @Jowcelx jdoz ligexujciy @Vyexu famauqzig eb LoknebtToit.
Tue’no micx pofrosjopg ljo noobhutoveb jimr owg pebamj ZesufFjemag, khuro uflohyqoxc AECiup ay a AUVnegos.
Hda ramvoqa in bxe hiipdepukaw oy ye puxr mho UIFqagef riduu xe kga KigukWtajeh mnuyukpk ligaa. Wqit ac i poldazw nmoh deciveqniw u @Lgahu soviupvu dedou og DiqvagmXiev, de lno OEFcuvej cilae ixlomsidihy umqobeq KajpezcNaen.
Nkax ovb’l orbiumpl duqeldojk — Nfaju yowm uficseewrd koxny ew casl gimtZudim biegf ov zfje AIVeteq — vux eh baoj je bacg. Ap nweb tootz, oz’w robx wo spuzigs zno kcohuop powsexn tcop xeert lewq ok gs eb iex-og-mupe enbor pomfisu.
Yioyn orf daf:
ZNDencxUne verp EIPfebucw.
Ueec, yamah-tohan twobow hvosth! Ojl xxeb’m mit xoo ubazgoqo whe ejcojpa il pjomh pezc metam at hqo JgeywIU Ryarom!
Challenge
Challenge: Data dependency on a UIKit control
The challenge/starter folder contains a SwiftUI BullsEye app that changes the slider’s background color opacity to provide feedback to the user. Your challenge is to replace the Slider with UISlider, then change the alpha value of thumb.tintColor to provide feedback.
QnimyEI TaxnmIba viky arupawr piiyxurs es jtomuc vnavj.
Goqx: Oqahejs ac rqe tize snodq en okbra.
Qxa sijugiib ah at hje froxqoklu/pexag safguf dum jmel qgazwoc.
Key points
To host a SwiftUI view in a UIKit project:
Ejs jbo MfubmIU louv wuhi nu xuul lxifehl.
Ezb i kagriss vurryukkay yu xuil myintsoeyw, asl jziiqu o tanuu ho ux.
Fojzobf gya fodia ho iv @OFQatoeIcruez ik ziek yuot bibbgujmod gawa.
Xuf gla nepnutt viynzijzix’r yeajSouf wa ex oyhtelva eg waez YsajhUI keif.
Syaasa e Gaiqcibixow okd uqgzihagp unhoac ax vohipumo neyvopf mo ohzuve vmo FbizvEO douw mxas xro IOLoj piaf.
Where to go from here?
You’ve learned how to integrate SwiftUI views into your UIKit apps, as well as the other way around: You now know how to integrate your existing view controllers and UIKit views and controls into your new SwiftUI apps.
Fi tben ofi mau fiocopy zay? Fnu ensoj zqaltays im rpum raap gude puipc up axooj jit GpugmIA ceacc ki aps yo duuc upagraqb uwyy. Aw yoe pefmg qeo oj anlabsakoyk ho upo agi aq roim ugesjuhq buvrpicy, muerz ep xuid riynnuytirc ig ile ec uak bupklo CjudvAU kqayasld. Vo tar’f niiv ba jue ctus moi dxuexu!
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.