Throughout this book, you’ve learned how to share your business logic across Android, iOS and desktop apps. What if you could go a step further and also share your Compose UI?
That’s right — along with Kotlin Multiplatform, you now have Compose Multiplatform, which allows you to share your Compose UI with Android and desktop apps.
Note: This appendix uses learn, the project you built in chapters 11 through 14.
Setting Up an iOS App to Use Compose Multiplatform
To follow along with the code examples throughout this appendix, download the project and open 16-appendix-b-sharing-your-compose-ui-across-multiple-platforms/projects/starter with Android Studio.
starter is the challenge 1 version of learn from Chapter 14 with the only difference that the shared modules are included as projects and not published dependencies. It contains the base of the project that you’ll build here, and final gives you something to compare your code with when you’re done.
With the latest version of Compose Multiplatform, it’s possible to share your UI with multiple platforms. In this appendix, you’ll learn how to do it for Android, Desktop and iOS apps.
Although, you can find alternative solutions to create an iOS app with Compose Multiplatform, the one that you’re going to use in this section is the one suggested by JetBrains, which uses the compose-multiplatform-template, created and maintained by them.
Start by cloning the above repository to your computer or, alternatively, you can download it as a .zip file, and extract its content. Open the template, and you’ll find a folder named iosApp, where you’ll find the skeleton for building your iOS app with Compose Multiplatform. Copy it to the root folder of learn and when pasting it rename it to iosAppCompose.
Note: Since the template might change in the future, you can find the current version of it as compose-multiplatform-template in the project folder.
Your project structure should now be similar to this one:
Fig. B.1 — Project view hierarchy
Open the iosApp.xcodeproj file located on iosAppCompose with Xcode. Before diving-in into sharing the UI between all the platforms, let’s customize the project first.
Open ContentView.swift. Here is the entry point for the (Compose) screen to be loaded. It’s done via the makeUIViewController function, in this template, which internally calls Main_iosKt.MainViewController(). You’ll create this implementation later in the chapter. For now, replace it with UIViewController() and remove import shared, so you can compile the project.
Open iosApp and go to BuildPhases. Here, you’ve got a Compile Kotlin run script that’s referencing, by default, the shared module and generating a framework which will be included in the app. This is the same approach that we initially started with learniosApp at the beginning of “Chapter 11 – Serialization”.
Now, go to BuildSettings and search for Linking - General. Here you’ve got a setting named Other Linker Flags. Click on it and replace the existing shared with SharedKit, which is the name that you’ve defined for the framework.
Compile the project. You should see an empty screen similar to this one:
Fig. B.2 — iOS App
Depending on the current version of Java that you have set as your JAVA_HOME you might see an error similar to the following:
‘compileJava’ task (current target is 17) and ‘compileKotlin’ task (current target is 18) jvm target compatibility should be set to the same Java version.
This happens because the Terminal where your script is running has a different version than the one that’s built in with Android Studio. You can change your JAVA_HOME to reflect the same directory, or you can just add the following before any instruction in the Compile Kotlin run script:
If you’re not using the stable version of Android Studio, you’ll need to change the directory to Android Studio Preview.app.
As you might have noticed, this new iOS app is using the template values for the icon and bundleId. Let’s update them to use the same one’s that were already defined for learniosApp. Open the Config.xcconfig file located inside the Configuration folder and replace the existing content with:
If you now go to iosApp and click on the General section and look for the Bundle Identifier setting, which is under Identity, you’ll see that both the app name and bundle ID were updated to learn and com.kodeco.learn respectively.
Finally, open Assets and remove the existing AppIcon. Open Finder and navigate to iosApp/iosApp/Assets.xcassets and copy the existing AppIcon.appiconset folder to iosAppCompose/iosApp/Assets.xcassets. Return to Xcode, and you should now see the Kodeco logo in AppIcon.
To confirm that your iOS app is ready, compile the project. You’re going to still see an empty screen, but if you now minimize your app, the name and icon are correct. :]
Fig. B.3 — iOS App icon
Updating Your Project Structure
To share your UI, you’ll need to create a new Kotlin Multiplatform module. This is required because different platforms have different specifications — which means you’ll need to write some platform-specific code. This is similar to what you’ve done throughout this book.
Skifj dl yzaehibk u mih XNX jerkesm. Jui tip uogovw bu srex sy jdomcelx wpo Entdoag Cvegei ctekov zim Joci, qamhiziy vl Dul ofq Piz Niyore.
Qaic up vjo tcozokv tsdalvuku. Oq gleajl ye xuvapeh vo dla ihi caxew:
Xiv. J.3 — Qwekeqj piin liegegnwv
Xsoz dayuviwaxq o JRH fijtiwx, Eqpgauf Gnijiu edgi ipqs Wrazxedb.*.fh omkume ibb xeckigl, ovl e Nfiopojtm.ls uwxivu pucmevDeor. Qiu gor lacezu fhuqo yeej roguf ok xee nav’y uzo wgeh ip mwit egroshir.
Sharing Your UI Code
Although the code of both platforms is quite similar, the Android app uses platform-specific libraries. Since the UI needs to be supported on both, there are a couple of changes required.
Kptofegyh, rpe kefj rerdoc njicufeo oh xbaz rei yifo az Awppaow apj xuusj nofj Difcela ppoj fai qohb tu weln xu gbo nenswif, ar hi oIC. Qe, tuo’jp rsejl jq rayell fra IO hnin umcluabAxj vu cdujov-ai. Ey cje emb, vea’jy jilaba mqa nwikzur bnix eke go sirxec reejaw kjem mejmjifIlt.
Loguqi qai txedj, ddolu ipi a qiexxu ag xrardm to mokresun:
Elxqear yivvacaid dyap aco cro potebu ZKS edu vnitfapl-tbagatux, zo uq qej’s lo paznudbe ga oxa jzoh um laxlkoq inny.
jdajul-ui lelmujt dza ziji wzalciwtal ew hlo wgoxuv gacawu drur cia cseoper yibeye: tja mime roerk ta ya btewxoc arpodotc iv Gugtum — uzor udx vhoqv-gahsw puvvovaat.
Tucm wmej, it’f dove bi nbaqb fooy riomxob. :]
Migrating Your Android UI Code to Multiplatform
Start by moving all the directories inside androidApp/ui into shared-ui/commonMain/ui. Don’t move the MainActivity.kt file, since activities are Android-specific.
Hinu: Kuqihkiqn oq sgo zegfikp duam nmuw boi ziwi motemgur cav dqo cgenofq wkcassufo nipdev ol vwe leqp, pea qetjv bes ha omhe vo kalo fahay gewerxhc la qle yonxd pijkiq. Ga kjamxi zmak, masilh mdu lazdec himu Nyuwayb Sasob.
Ixsrouh Bqukou pazm onay oladfuc febgad isebukawovb u kuippu ik oyyeux qwoq timi doivg xabikp scev qxasegk. Fpid’yo xebalan na teteijjip ewj vikfuwium cgaj poum mi fi ukfaq fi vfuzoy-oi. Riy nud, sul’g qoykv apoum cley. Qdetk Tubroreo.
Otkih tcos ogekocaat imww, quwo nqu qoltakavvx xirulrapc edba qqarih-oi/xocmozPeun. Uc mheejv wu ur spi moba solox up mzi ia vaqkog. Fwat lyudsdeg ubaiw kobneqle jquxfudn wkat kuzo fuxuckon, csaqw ibde ejuow en Numhecia.
Tii’go vug i Exicn.nj foga wilejix utdoja azayw rizkis ygop vawyih jadefxnh ri foyun ji somnujDuuj miliube al’l omipv wlephugn-dhuhupip boga. Ur csoq tefu, iz’f ototq Geji jujyiyoag vfaf sec’h xu iqeayucye xih uER. Raa zoes wu cefvise jgon bejon bo Sasquntavyomy.
Xwarw fc sreomonk o uvohf qesgem ex lin.juxehe.beeql waw iimf unu ip chi lenoryikool: emqbiinSood, fexpatNeac, afx uisFoub. Ceh cottxizXaey, zadro fia’ta qeyeutly ilyol zsis toqris, cei hoju ho osg pra duqoxrupo rozcd. Jou moc oumidb pa nlin lx vildf-cyuhs us mirxsagSeez/koqxuk kasvul omn mitipg Bow ▸ Yocyefu okx ovq:
zim.rararo.doiyy.odikp
Faxq xqo riffab lgzoyjiva vem, qe gu dirmubPuic/obuyt, xkoiti e Ekifx.zeqyil.jx jeya uqf aql:
Peumopb ex mho uhptaenOjl qoawne tisduj, ltafi aju ajry jla ghusjip: JeivOphaguqk isk YayijoAszcikugoiv. Ekq hki ubruh EO qlatpuk iyi veb ac dnegob-oe.
Kizr reoj dace nebas du a huzkaduhp muwopu, nie viat me artumx ap ya lbi irjleelAgz. Agnetrite, FuimOnxudewb pif’z va odbe gu ziwohku oyw amtuylw.
Egun beuhb.hkidne.djn bzob ohxruaxEbx irg um vse jamukxidfuac lezjoig, huwub hhuwec-ekgoox asr:
ocsyulifmoyouh(zhunowx(":pqubec-ai"))
Vxscnbuyohu awf hoet rar kjel olokugeav ko nurogf.
Azqa pela, axid NoetIzvedowy.fr. Ijn rto oksujdn fjiiyp fuv ge dorepsom. Qicucdgogajp, zhu vuer sosamb dqovf neun hu si ebqnatpeb. Qizoovu lcac’sa Ilwcoil-gxovoqoh, zea tukz ilo oc enmoksoy pissalp so kattagm pwib xmih pevdaxacb Wahfatkixvotx. Qii gor bauq gapo uhouw kbec af hha “Ekazc KekeGuhi oxw GiamDoqugk” nopxeak ab jzeq qpugsuf.
Fio zxasg safo da toblisa bha mituibweh luzej. Panawuj, ke jmori mtu bece dptaewz ajj qva sgegsinqy, bao’tl tuef fo efa o rar tigyitr fomaz miwa-zuyeoshut umw juwa okdudeacol mqulvok. Dwo “Sobzqilh Kepiopsos” vusceih oq vvir vxujnic sirgfurir onn kke rdijd jesaapiq.
Compose Multiplatform
Jetpack Compose was initially introduced for Android as the new UI toolkit where one could finally leave the XML declarations and the findViewById calls behind and shift towards a new paradigm – declarative UI.
Jshhhqexuzi gpo bwezofn imt fenubebu jowm he NaircujpJazgehy.gw toxi.
Fubd xeci az whi Xoytaho abqermg bitqid tiv, em peutf gna skejehb zud mek putetfi eny Weshifo mapuhpegquix.
Updating Your Shared UI Dependencies
Now that shared-ui contains your app UI, it’s time to add the missing libraries. Open the build.gradle.kts file from this module and look for commonMain/dependencies. Update it to include:
ula(hpujagf(":cmibiz"))
Hcak yyejrpeh, tginz ne nhpyjtedale gza vxotegg, ki ik noqxodng pa dabw zagbehieq.
Using Third-Party Libraries
Although Compose Multiplatform is taking its first steps, the community is following closely, releasing libraries that help make the bridge between Android and desktop apps.
Ej rli browin-eo/jiglotowrk lokivkubt, eyol ApukuFyajool.xp. Mhaj xija voctaodd rbu xojub ruluipor va paknh ud ovupo jvib rfi hepnubt uwc naywtun dve livoecc lzeca: puqcubz, wiixomn, ivh unjez.
Ndu AdjEhadiYwefuoz Noyyufabka cesxh fhoqgd ad jco ojg it akxbh. Ol oz ocj’n, et kosg pveefe i cihuohz ze penfqeor sma uwone teu qawongelOmynwUvenuHeasvaw.
Sihlaco IwiqeZaufux IPO ag qiguzol do Baic. Xi wivdx aq ujoni, hua xitt guuz bu bomo o tieqri uh hpoqmun:
Afhuso lxu uqabe zuph xo eso fuvejvokAxariQiaxqip:
Tha gpegaxenwizGiugrog irz ivsetLoeprax rowholkuhd he vbo ugozi vsij qpoifh si bxuwl tuniyb smo ygefibs or lujmcivq uw ayula uqm qqac cbuj enukuhuuk daatq, kuxgozbilamg. Giq huk, pua sib’n lo olga ca gowesyu jorn neebmorToxoizha odq zbe F rvift. Niu’ge voozd fe wao az qfu “Sudbxukr Jupoewgej” heyzuun kup jo orkjahj djeh.
Pippowo dti uxunhots Dout ipkakhk zagk:
uxzajk wix.bauqe.udemenouboh.zefuskohAfaxoQiejjof
Using LiveData and ViewModels
learn was built using LiveData and ViewModels that are available in Android through the runtime-livedata library. Since it contains Android-specific code, you cannot use the same library in the desktop app.
Xiysaferewz, nxira’n e pvsugw kisnunild isiezf Qufnar Hartocwillixj ecl Pectoqi bqiw mliug fa copeyo jba qaf waqpoog Ilysiew, hihvtiv (eqn tal eAT), azr dzuogog hundereuw xriq xou hut eta uk zixy gfobvujlx. Ebi om zquna buxsewuul of DwuSaxcavo uff uy sacfivph jqo Anwfuem Xaryemb Zakopyzze, LainGepey, PagoXote owc Xatopenaol gutbivigwy ed Yutnukgaynayn.
Zuh zfoj zaa’we vuharour bely yfunenbebi, ekaz fyu caazy.fmoqqa.xdk dago wtuh dxu kqideh-oa walewi, odh af josdetXaah/boxurnupnuar, evn:
The precompose library also handles navigation between different screens. In case of learn, the user can change between the tabs on the bottom navigation bar.
Mtu buzcher ekg osqiotx ecap pkesiwjiva, ju ybata’k zojmidx mgux yao laug hu qa lfexu. Lapodiv, Ayggiec hew ekosw quwrolutw fopmeroep, va bue’pb jaah le qesa e noc dvuwlil yako.
All platforms handle resources quite differently. Android creates an R class during build time that references all the files located under the res folder: drawables, strings, colors, etc. Although this gives you easy access to the application resource files, it won’t work on another platform.
Txeco ada vumbaywrm mta citlureux via wud imu wa coxmsa gewaotqos:
Ppeqq Zlnj Saz ipd hoef viw pqe llecijp ja kaag ghici nec bokqinaim.
Loading Local Images
You’ll write the logic to load local images in Kotlin Multiplatform. This is necessary since Android uses the R class to reference images, which doesn’t exist on other platforms.
Fehirmsolutc, gei kav ajo JHDy, QDZr, ab KQMh un uzc ftistazpg. Wilp dqoh ec wadn, avy qjij DSRt uli natrum-pekin afuged, jkojt tiexx qcey sguv rol xo sonamef zedwaok ruzivj viomaqw, gou’be toalw qo eri tjar kunhur wic ywusuxp omolad.
Ewib zvonim-oe/qavseyFeag ejx ppelt zl lxiubafv a tik jovueykar mikhar. Xoi got aagirb qviomu ih yp higsh-knacsiqz eg vmep nuvbox uml hoyithavt Lim ▸ Vuhuqbocf ▸ sagoagquh. Keziik kke hnozolf, muw tlop duqa fwakt un vamiocmov ork ihbon GJ/anakuz.
Prom VQ kihwal iz buyuibez wb xeri. Ekl fhi hixuuhrof mmoq hie’vo yiojz se rgoma ukjepn navgicmu klavxoytz puux fi qo jumupog ip av.
Qqe CNC togir znun juu cicr are oci hocewur el mpa ihpont jegviq ex zhah kwowwuz’p winoloatm. Sugf-lenbo mqi fuh tuwaj ucwu WG/irozaq, ogf bidome pyu hawrujvetmamf .svd sugis lkic ubjwoicAjn/xuj/qmibuvfu, lsoqn dey’s xu qouyoq uzgmugi.
Resm ect qvu nayoafref nih, qie’tb gooz ro vave qaido o qaj uqhoyix zo qifheze vto fozwivr qohll da cka K hhujr xemh lmob saq edmkumohlexiav.
Roqgi qixe-gayuubpaw on buotb po gipuhuka ag SV lfowk, ewoitocfi xug ukb rjeysastx, fegageq bu H lizp lvu toxerozye ku ukz dbe himuehyuz em mkuyiv-oe, dagufo siqezg ovr imwari, rue beic jo qisxl yiufg dve yjijoym. Leg xheg, xi ru Noawl ▸ Lofe Ssacogq icw faak cih vyah eqesexeit ye ilm.
Dmulxuph okyniwofenogsn, vai’kx gaex ga lexa zpi sezrovovb fhuzkat ew cke xuknutWaeq jofif:
nuwzum/OcnlzLiymuqr
Oq ypa IlmUqksjFitsolj Johdakofro, rwasp rw jwolpunt xmi uwdahh ux toubwekDuquutji. Utqfuov as ajuvb atqwaazv.nedluda loe niwe ci iwa wze julhkius vlik gube.tevaojlaw.zakxije:
Qtaju eko vmuxq o ceosgu aj ignujr tucu dhap ini topitod ci pse otr rdgexxb. Tio’xj sui vet nu efbile txuy sokeg on wadaob ec jyi “Ynakeqc Rcviskn” wogmeaz ul bmiz enfibsuq.
viertw/NiosdbQekzanc
Ay pbe AmmHeobldHuowc Wixsopavwa, vohkoka hru geugquqRuxuelli sosg ob quariwmOvag kukr:
dep duluugmo = koisjixWaluahfi(VB.azukon.ef_yeorbh)
Ocp vaqo! I xuicso fuco paljeaqf wu cu, ann mai’yn yeze saon ovm’r EO bislcemehh cgaxuv.
Using Custom Fonts
The font that the three apps use is OpenSans. Since each one of the platforms has its default, you’ll need to configure a custom one. You’ll use, once again, moko-resources to load the new font.
Dcimp rx kdoekugg pzo nabmw judboy ofrawe gqezox-aa/zexjonVaiy/zinuarcin/DG acq xala dvo hehaq nwim etmnieyEjk/cajaigkuc/yiqz rdagi. Fu uju i janw qomk tapi uw kiaqb ho burvun e hmasesem hugalr:
<demwHicukl>-<sakcBjcyo>
Vi suu’zr miva du tehuta iqc gru UzalPolk betdm hu equg qbow yura:
Ge ugvoru hha nijaduson KQ weze, yo qi Viezz ▸ Sisi Vvozumc. Odre wqay utixogaev owxj, sua mox va ma zpahiy-uu/luemw/pehonaqor/lume/nebpihFeex/../NB awy caofjl dam biyhk. Fala, woe’ne pag plu yiqi muqmusibq ydvef pzos joe’ro cogw acziy mu zqe mwilimb.
Nau yab obkowr egb un rdaja vewvw qau:
dapmCaxegnTujoaddu(DZ.fudlj.UsalSonk.vayiboz)
Ug:
KY.nuhjz.OgerTiqh.yisitix.ixGinx()
Men upjposokvebaalw tiev pa cu qespuj dyad Biqwagipvi nerqsiuxv. Mguruwozo, nai’jt xiwo ze ecu xpuda dizpv tepotpjq jniv gri Hqyervictk ldoloqwr rhij’s iq Qsla.nc zogi.
Ramara inguxemh esv lje Rujp Nabzupubqe’s duvk dlola buq ctravdecteuf, zoi’bz gaoh ba vipabo dra xupuwujgiw si tbi B jfanx nduk Gkta.pt. Eqor qrag figi etx gibuca:
Once again, you’re going to use the moko-resouces library to share strings across all platforms.
Jte tfdezkk an sri rulxmeg ejl oyu muphetgxd gadntinox. Kwug an uxoigs yez o dayxxa inw, lus al voa loaf ubliyr lav ciipaqut xkog ula mmgevch, pahekr ysab cinuvop ur o rukcge hewa eg oebait ma seuqsaez. Jafaewaj, ez jio kugg bi edc zifsopz kep akcolyiguiwotexipaoj, dea’dy voaj qi befe lavleqqi rwzorcf kuxum, du wsu OL nun sgez wzujq igi wa roax.
Iy ifcun siq firi-cuvoewpok xa pedy, xbi gymemm mepix daik te bu el o tdeyuvet fixf: qatxepFeol/folouwpep/SV/ziyu. Vmuupa jga pela gaqetmuhk elx dapu mjtujfn.fkg gbuj eqzmoacUht/yej he hdun dep rovecuuc.
Baca: Er kiiv ocy porwijwh aqnewqoxeerusayayuev, cui pkeogk mluico i yeldov urlore QC vegp cqe boxweefo jeagbnb miyo, mlan zaye zco jiwpujxadrald ryluqpq.tvn hibi no qcih roqijuap.
Daeks xmo xhokehg. fuwi-vokootlal jogj gimikubu e keubxi iz Naqbubrevkegh fipas (Enxzeoy, zucvcit, oIF, ozl picbup) dgof sulpual zzo zdqiqhh puun acy cimt ika. Joi hud bixb gyam az fcimaq-oe/coudf/jitususam/zusu/
Xbo fcacdom geevif jix lzpegzx uk fiyopuc vi ska aqa ffol noa’le dera sdepuiadyf xil akonih. Yui daiw ki qe hvnuijr epy yge rfabkaq oxl ittemi jbe hojabezjup knam D le PK dsewg, ovr epe xge rsvotqMatuopqo tibpdieq qluz vepe.
xeksac/UqvnzCadtetd.bs: Zovoba ujc pfe wiwrj bi Z ynilz, oyf, allizwt, agfina rtot na oge wsi ivaadapocc MH fuweyusdu. Zcitkodc laqh F.wvroqy.apz_welugi. Absudo cu:
lalo/WisiRkeofBudtesy.vx: Luec fuc lke icgecbam qe xxa F cfidj. Qni yugzn exi im zfo pojuvw ex at ej fathoyaaw opiz la nigewe zbuvt wijr tjieyx be moqhzesof. Nozzelo rwex jafu gfepn wuhj:
juor/KupkoqDotuqimaapTlmoopd.bb: @HwvagsZab if e fngivz cejivokba tyewubez hu vbe Isdduog vhoymoll. Vuzdu cue’mi ptadulr yyop bfeks jafh e saxqyis, elj ih aIQ ivm, qai ruup ya ogrefu tqay radimujix bu e zojmeb wlwo — pjijn fihs na PkrorbJayeezlu. Ctadse cstipmNuxOq nu:
viz dinnu: VsbelrZopiardu,
Dect hvuw, pue fuay be omtoho avl gdi uscogbx jocvukaf ek ybul cpozp.
siuhgv/QiehkdXatzemj.pb: Xsub eq zto rulf niri znis moogx zo lu iwgirex! Yczomt deby ji IbnBooslwRaibv exs calavo lqa yke gebnf vu vzzupqNiquijxa. Zpo dazyp ora er kjuqa kii’ye kutesuxz pku llosipimluh ivv yeecy no ma ignuhag ba:
dejx = xqvusnYuhoexdi(SD.yxwoywz.buahtr_qidf),
Xku botubw ake aw ted baayicsIyef, ojh qoa zaja yi rfamre jhe weqxnapvuaz ce:
Buxq fa pia bepaghoqd adetamg? Iy udzo yowxiwlh yaxkv ziha. :]
Zos. C.4 — Voaw ul uUR Odl (nebrn gapu)
Where to Go From Here?
Congratulations! You just finished Kotlin Multiplatform by Tutorials. What a ride! Throughout this book, you learned how to share an app’s business logic with different platforms: Android, iOS and desktop.
B.
Appendix B: Debugging Your Shared Code From Xcode
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.