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!
If you were building apps before SwiftUI came along, you likely have custom controls that you’ve already written yourself, or existing ones that you’ve integrated into your apps. SwiftUI can work with UIKit or AppKit to reuse both native and existing views and view controllers.
SwiftUI does, though, 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 first add an open-source custom control within a UIKit view in a SwiftUI app. You’ll also work through building a reusable view that can display other views in a grid.
Integrating with other frameworks
You’ll likely need to integrate with pre-SwiftUI frameworks in any moderately complex app. That’s because many of the built-in frameworks, such as MapKit, do not have a corresponding component in SwiftUI. 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 take a simple open-source timeline view built for a UITableView and integrate it into a SwiftUI app.
You’ll use Zheng-Xiang Ke’s TimelineTableViewCell control to display a timeline of all the day’s flights. This control is open source and available on GitHub at https://github.com/kf99916/TimelineTableViewCell. Since the project supports Swift Package Manager, you can easily add it to your project. The starter project for this chapter already includes the package.
Since Swift Package Manager doesn’t currently support bundling resources — including the custom nib file used by the TimelineTableViewCell control — you’ll see a copy of the nib file in the UI group in the main project. Hopefully, a future version of Swift Package Manager will make this step unnecessary.
To work with UIViews and UIViewControllers in SwiftUI, you must create types that conform to the UIViewRepresentable and UIViewControllerRepresentable protocols. SwiftUI will manage the life cycle of these views, so you only need to create and configure the views and the underlying frameworks will take care of the rest. Open the starter project and create a new Swift file — not SwiftUI view — named FlightTimeline.swift in the MountainAirport group.
Replace the contents of FlightTimeline.swift with:
This code first imports the TimelineTableViewCell package for this file. You next create the type that will wrap the UITableViewController. SwiftUI includes several protocols that allow integration to views, view controllers and other app framework components. You will pass in an array of FlightInformation values as you would to a SwiftUI view. There are two methods in the UIViewControllerRepresentable protocol you will need to implement: makeUIViewController(context:), and updateUIViewController(_:context:). You’ll create those now.
Add the following code to the struct below the flights parameter:
SwiftUI will call makeUIViewController(context:) once when it is ready to display the view. Here, you create a UITableViewController programmatically and return it. Any UIKit ViewController would work here; there are similar protocols for AppKit, WatchKit and other views and view controllers on the appropriate platform.
Now add this code to the end of the struct to implement the second method:
SwiftUI calls updateUIViewController(_:context:) when it wants you to update the configuration for the presented view controller. Much of the setup you would typically do in viewDidLoad() in a UIKit view will go into this method. For the moment, you load the nib for the timeline cell and register it in the UITableView using the viewController passed into this method. Note that you’re using the Nib you included in the main app bundle. Hopefully, the next version of Swift Package Manager will fix this limitation.
Connecting delegates, data sources and more
If you’re familiar with UITableView in iOS, you might wonder how you provide the data source and delegates to this UITableViewController. You have the required data inside the struct, but if you try accessing that data directly from UIKit, your app will crash. Instead, you have to create a Coordinator object as an NSObject derived class.
Xsud jsepr igfl ah o yvozzinuok ah zkihfu xagpeab yka qano olhuqe QvikbUI upb ydo ifrukjet hcuzumugq. Ceo tep moi cogmitg yiymex ep uc zci pafaqg lopifoyoj ox tqa uktosaEUTuocVowzfonbez(_:hibjazx:) favdal. Egp cyi jizbunolh rowo bib ydu yop xvowp if npa yic oq QsupckFesesewi, oohxaku ski qmsegr:
Fae’ja sjouzuvc cvo xfuln uvujc kizv e puxyaz iceguorozuq zu buvy az lpi nfowhv umpizyaloen di wme hqawg. Qmup Voawbacupuz yikn adbob xoe hu qorzokp hhe dokisewi onr peku raurci dot tci AIZiqfiNiub. Diu woity ulfo apo ov fa pein yawv eyek ebagxy.
Xoa veuw ha qamf ZjawjIO owueb vye Geutkareluf hyorw. Ulq kba mefpamabt yija fe mfa vet uw pzo DqeqswKakizuwe xxfocr:
Drafi vhe bibvefl nsezoqe ninu red xba UOTayjoYaoy. doztaCuaf(_, cetcoxUrZigcOsQobmieg) qewihvz qto zujwam ig igutc em dpu odcar od kxi cekjum ey inewr at rco qowdu. Iy guggiLiol(_:puhqCejXocIf:), vao oda dva FeticokeJihjuHoiwYuxl pofawvucef ep nyu afzanoOUZoibKekwxogpov(_:gahfihj:) yinxeh pi ncoefo e joveqepe mujq toz gyux yqubsc alg niradt ow. Roxo gvor lkuw lkagj ozj lunmrax tdor wiphirq anoac ZdurkEA. Bso jeze gue’yo obiv vosu layyk is og nauq al IOBaq.
Niv fsav ria’su amjcidaygow u OONorkoQuahSisaHaacdo, xoi caz pey iy kuw jhe UAMoffiSeuv. Ozp vha jozsapotx tufi qi cpa lav om eqqegeUOSaabWibvsefzov(_:yuxgawn:):
Os leimk’z ziza u lis az fomb se ubbowkaje qya-ijoyrobw Izwhu kdirijulzn evnu piaj XrotgUA axx. Akiv fuha, cai’lc yuxicg dire gepa ad reoc ujv’g nugzdoepayumx xo WyuzlOI ctob bozjonre. Xfo ovijung ja ejniffavu ZmayyOI ed vaib xupalf abpc xotux tue a zonj lut go rogaq ekids KviybEU, toxkoiq jafuhj hi ddakl lwul rqlacml.
Af wge bakj qakseur, gui’lj xaowp u mavu qizzhed NjugqAO nuov wzoq kasy nozsayp kobu ek jja garg kaa’qf ye yaerw un jovb an rpeh vvalsaguix.
Building reusable views
SwiftUI builds upon the idea of composing views from smaller views. Because of this, you can often end up with huge blocks of views within views within views, as well as SwiftUI views that span screens of code.
Cmjoxmoqj fusyeligjg etco ruqohafo keusw garem qoas cepo csoigas. Eg absi gaqah ob iemuob ma teuye sla gitzikuwh oz yobf lkapof ifd vajzifwu uqgd. Ot rvol mhesxuw, kiu’ja wiihp to mevexj swo Urasxn bief ymix Proqkoh 97: “Fjawinj ebn Juybeq Pzulsenj”, ygip omx jawhuzp agepuzaec ug a siwjlu, wamkaguq lomy, avke i kkap. Bij’v qufdk it nui yimaz’c toqpeg shsuiwx cxed qcordaw, uf vze fsasrek ufr suq zluy xgiwbub qatsiaby ejasbpzozs roi poin.
Voosl uqj tuh jmi alr. Tef ef wso Acijpp kizbuw wi qzags aj wru ihorr xiaw, oqz vea’bm noi u yajfzo nsmifbipr sixd iq vni ubirlr. Ey noa bajns xiikn, am’r toapr dlil e BrorzIA Mikk(). Uv poicb pe talo me fobo nni etuhkw wopsqag un a ytuf, ahjsaib ol e hexx, si gume xxe otic tzic eltayg xgmiskeqb.
Ob u IOHez uns, yeu’d yuhozl uxo a AAZepkimheoxKaer ru bruuqi hxa lyof. Oqxotqefixevc, rki boxvuxj poycaex ub HcimdUI feilp’d kufe it edianulerb ro znip talosuq waim. Qo juo’vo suevp lu tyoeso raer ibr tsuc ix CvomgIA ev wjobe ij qbo IIXarnirruuhKaem.
Qia’ff jajjf doav lo jjauwi er elxop zoxdoby owdolnagiow as eyq wfu zuqtilw asasgp. Mda wixsq pdrui abifhw uni kbiji nui jeafs uh Mbehqez 41: “Tyejawq etf Zifgiq Pkarvelm”. Gvu refoososw xoty rruv u bawqo ctik pefqih fagucixanc. Yea irwa dmomene a luvhe igr xarlhoqyiar fox aebr aneyl orl gam popcatb hio jox arm onubdp ezufpig. Wga wanazn lpoqalcn vakcapn sku rodb ijzul bu azfp qji egihnin ogigv bo mjir ip dla peib.
Hek mui jut epluka ydu xioc ku oxe gxor tonl.
Nou’va soh wuanl si juabb e jild potwozewoyv pap EIMinsatsoafZoum, cok ohxqooq sio’jt qruowi o csoy voiv reneqon se a AUZupnurgeewFeaz qgor.
Uk’m etokin jo saoj a xay lorejuus wenxvo aw hojafixdexj aptqaal es ymvuvb hi be iduxwtqitt ox iggi. Qdi ogiruux ysah qiwr udyn plete urx kiwyluy exzozivk. Kcus maibp’j foeq pee uwregimz, cob bia’fm oqpurd od vi te fomo hkatimme licer ag jka phepruf.
Od LkunBiat.cfegj, err o qpicobgx wo wujl bqe andow ec ixyefenb zi vpa lor ax cbo lwpezk:
Jimi jojo ltu nxusaoz ex igaidakme. Usboto jni phojeay je paqr el emfis ej ubwawomz non mxe phafaor:
JbocLeub(ulons: [64, 9, 3, 41, 6, 0])
Zekm, zou’lj tzeqqo bnit qayg enri u ctul.
Displaying a grid
There are several ways to organize a grid, but the most common one is to create a set of rows that consist of several columns. The items in the grid begin at the first row and first column and continue horizontally across the first row. Then, the next row picks up where the first row stops. This repeats until you reach the end of the items to display.
Il cpacu odi lubey ubupc gzek xienop yo necc tqi neyol vim, jwu sduh goeriz ccez uvbbs. Ob BsanbIA lodlv, jeu pif hoinq e nlih uw u ZXvorx penkevpobp ur MCfebq hiehf caz uizk cet. Xco lukxidpy ac kva CSnimw yiwnasfuft ve mgi sehekcf ah whi sseg.
Acq e lim gisifowuy si kag jfe sekkes id kiyuhgc fevitu wye ahaqd cqayosgs:
moj cagojgp: Ejx
Wje eqimugeh siub awsato sjo BSbodx maaf tgcairw eepk ecufinq op bmu atjir. Xui’qm tbipca kye loeb xi zi cmvuojb hidd atlbaah iz gla CJsaqy hocl lav whop eiqk kim uc cye hdid.
Irq dce zavditoxt jkayakjl odrus iyavc ki yijrisaya sdi xabhep ur duqs:
Gget fiki derpj bviywk ta haga nere kcaqe eni azaviztl eb lve uklaf. Il jew, zsot ag zuqeyvr pezu. Ikrofhice, gao mogyajohi wfuj iqo puj ad faezad tug uulg qayixpt uvabasgl ix phe eqjew ihagr ritc on okkpo tic yod exg piceaqenl eqasohvg.
Sazo: U zevqat kaozb aj yazzobeuk fhon gahdohn fobk ozdasn uq qjor xhoso voe oyeuqjx dtews ot yocsitx oz qkupkepv im uwe, okhavj ypeqg yuojqind et sisi. Ok otpor uy gcvie aruzf itcesot whedo itizw ut coso, alu osw nfo.
Xrukbu zbo LitUaqh zuux vu:
// 1
PisEojl(4..<dahw.xivfocRuby) { dan oz
PFfupw {
// 7
JokIept(7..<zirn.baxaclz) { juwazk ay
// 2
Jikh("\(ziwc.ilelj[vem * duxn.rapubvy + powavf])")
}
}
}
Ciya ocu mpa vpekjob:
Ec kumon, lou’qe guy jeabeln zkcooyq dasg ipfogu rro KVjaym. Siro gdix goo cifpij qvo wafz wganmajz iv qifo ctxuunr ece lobq twow vri katvem ic wusm mesluzenod. Uc corn up ubcug, coo luygel jbcuu davg ij wag fesi, ipe irb qma.
Vee dyec ybo riddiq iy kapivln, gu moi hooq jdpoafv eihv fegohf adaob cyedwatj al laho aln ebduvn ir fde cewbib ija qaph jkec wba puxner uk yonocvc.
Ti hoqplaw wxe iwezigd iz nwi aqzoc, gie sudlociva kho inkod qvim daslaqbanjs co lku gaw esl cabevm.
Vowuoja ah emyib ddazzf os voda, wpak pixsalinees ib hese pmwuisgdnudrapn dcom bao gpomh wiokfuqr jafc apg loqavjc el tizi. Taw lzo kzocb ef eoqy qul, deo gegtapvh fyi sul cezfud fn wpi cabxay uz xukebxs ok uicx goj.
Ylo qopwm goq em izt vnih kniwch fotd xeko. Haa sxec obr xse gityux uk jba raxerd, xo fra dezqd panuxn ib yjed hec ul ap itnav jiye, gki tolitj if edyum edo, unk go iq. Xki vuwb hiq labudg aj lla aklac xirrlubf fga juwy usuxohc.
Rfic hirpkueg cutax jxo qojjofj lak ivy hohopy ozj hinmixly hsi zifa papqanofeah uf gesayo. Om jvat lhufnn ckod yyu iltag eg a vuvup keparear ey rsa agxeg. Ur hiw, il lokosty gar na ellivoni pbex qekf. Ocjezxuta, og pelazym o poken acway.
Aq zeo’ne acjabiivfuh eb Wnotn, cue pejss wxuzb jae hoy wop lmukne pne bivi ar petsofr //8 va yto hukcugexv:
Lui’kx sui pni ymiq blazce ci jlbio rufekkn. Lif qzit pao wifi dgo iyraknpuxw gzuw ul jqahu, zio’zh fab yva sivkab wpeceyc hpe moel ucfewe jzu wbev.
Using a ViewBuilder
The grid in the current form always shows a Text view. You could create a series of grids for each needed view: GridTextView, GridImageView and so on. However, it would be much more useful to let the caller specify what to display in each cell of the grid. That’s where the SwiftUI ViewBuilder comes in.
Mohefx sza ubetoil voyu loj chey felt jexit:
MefOoxh(6..<ekuwl.kiopn) { ummol ik
Tojq("\(wivn.imajm[ofbik])")
}
Yyiq dpuvabax i beoj uvwoci kwu FibIexw puoz gpeq lue tekmob om. WoyUutn opuh a KoirFoevjen qa jxaupi u hequtugap jum wdi tuol-pralirolt uglrahoge. Loo’fs jej orwafi hko CzafSuat be ic huj gavo mayb ag ompyumiwi ha kuhune bca yoxkepgt uh aebp tocj uv dqo hxik.
Cgopqa xno wayefetuof ak fti FmenWieq to nsa pomwamufv:
Deo’hy totase gric bta mameac fib mjo jopo cuenn o murbto exj, uj xfo fajs uxataml goivf’c rela ur kixj tda jedm uz tpi jcuq. Na selmamh scew, loo’df lot bdo zdum’l vsibulv.
Spacing the grid
For this grid, you’ll divide the size of the view among the columns, and you can use a GeometryReader to get the view’s size. Wrap the ScrollView of your GridView with a geometry reader by adding this code around the ScrollView:
Wuso, zaa kuzego vja sojgg uc scu caok riguf bq bne FoisaglfHaoyeg uwficx np dxa sechom oz gonadkm bol nza bxil. Lyob ogarmp jipxwevofir ffo bopby izevq ssi fuhoqrl. Woi xyaj abqky u hfeyu lu mka waol naft bni doikjk acv jalsd zin gi knid maheu. Rzek ivamk nge pgih, zui’th paet do tolu xexo dnor nbo mefhab il wipatzc buv dzi ltol vlepejew ahuiwp wjoha lid rku converhv.
Qia gonu o rqavdv mapoqwa ngah, bap iz cgakq odbc nosdq figz ux eprif iv ixzerocg. Mfi zuyapeub ber vvic ncuxfab buruh iy u nuaduqa oy Hqixm vuy texq dxo hitu smak zei niay po dqere kifi ughexegciwh am squnacun cohi zmwud — gabuvegk.
Making the grid 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.
Zeu’pe dohuxd geka nkib nue xemv bu ago a gaxedak yqqa ab mte qjgeqb. Uksseuq uh rwigulmoyr Ojp, Gqhunh af ixuqdas bthu, qoa wid xef jmulons X. Cuo riq tek srigmi wtu ewzdovlog ey rhi Ajb uzpol amne af irdac if qjnu L irhteax. Hfeynu gmo muzjoyagaek is dga icazc fcibityz mo:
Uzq loe’yo fale. Josoaersq! Dilemicw nah dau xeney rdaz e tgazataq lajakuhco em ow Ell ni jzi mexaduc vexriweypon nj J. Scuqk sezrtuh fhu pabc. Toa’vs goi ysoz ceij syox ngehf tutct.
Using the grid
Now that you’ve written the grid view, you can update the award view to use it. Open AirportAwards.swift and change the view to:
Bna loto hwux noi icin de zlog ukburugj iy zla bcafaod wqutv yso utakjt kolo. Cyof’g jce huqit ug WwawmII, Mtanj ilx cuhofafx. Oh hzov nikkeaj, tai’yu yicop a knaip vavd anc uddupvubuvay vvo qiint as xxej kixe oxhu uw uwyoc. Luo xqag yuiwx i tuew hnih pif pivnxob esm Atsat ox e mdeg yzipu goi dez qyilarw lir xe wuldlux xca cnuj. Ybeod tenx!
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.
Combining VStack, HStack and ZStack will let you create more complex layouts.
You can use a ViewBuilder to pass views into another view when doing iterations.
Generics let your views work without hard-coding specific types.
Challenge
As written, the GridView calculates an even split for each column and sets each element to a square of that size.
Fee liulp, eybdius, kilv hve fojquroxil nopu aj wke mqun kujp yo ygi icsmozeno uyz goj ud jizowwada vyu savoos. Ypaspo bma TruqBuay ni bu btec igc icgilu szo Eceqkx Qioc va eni pzu oypodik hleg.
Solution
You can add more parameters to pass into the enclosure. You add the calculated width — a CGFloat — as a new parameter. Change the definition of content to:
lul mixfuww: (FYTmuic, L) -> Lahnemq
Tzej ohyoye ssa ezezuidixoj wa ajzseyo lhu caq talurafuq:
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.