As you begin to develop more complex apps, you’ll find that you need more flexibility or flash than the built-in controls of SwiftUI offer. Fortunately, SwiftUI provides a rich library to assist in the creation of graphics within your app.
Graphics convey information to the user efficiently and understandably; for instance, you can augment text that takes time to read and understand with graphics that summarize the same information.
In this chapter, you’ll explore the graphics in SwiftUI by creating charts to display how well a flight has been on time in the past.
Using shapes
Open the starter project for this chapter; run the project, and you’ll see the in-progress app for a small airport continued from Chapter 16.
Starter project
Tap Search Flights then tap on the name of any flight. From the flight summary, tap on the On-Time History button. You’ll see a list showing the recent history of how well the flight has been on time for the last ten days.
Note: The first flight — US 810 to Denver — will provide a suitable range of delays for this chapter.
List history
Looking at a few data points can be enlightening, but staring at a long list of numbers isn’t the best way to gain insight. A list of numbers doesn’t make it easier to get a sense of how warm a particular month was or determine the driest months.
Most people have an easier time grasping information presented graphically. A chart can provide a graphic representation of data designed to inform the viewer.
You’ll first look at creating a bar chart. A bar chart provides a bar for each data point. Each bar’s length represents the numerical value and can run horizontally or vertically to suit your needs.
One of the basic drawing structures in SwiftUI is the Shape, which is a set of simple primitives you use to build up more complex drawings. In this section, you’ll use them to create a horizontal bar graph.
Open FlightTimeHistory.swift in the SearchFlights group. You’ll see the view currently uses a ForEach loop to display how close to the flight’s scheduled time it arrived for the previous ten days.
Since a bar chart is made of bars, the Rectangle shape is perfect to use to create one. Replace the HStack inside the loop to:
You’ve also set a static frame. This change will allow the text displays to all take the same space, making it easier to line them up.
You set the remainder of the stack to a Rectangle shape. You use foregroundColor(_:) to set the rectangle’s color to help indicate the delay’s severity.
Run the app, and you’ll see the result is a little underwhelming since the rectangles all fill the view and don’t show any additional information.
Initial rectangle
A shape is a special type of view. Therefore you adjust it as you would any other view. To change the width of the Rectangle to reflect the length of the delay, you’ll add the frame(width:height:alignment:) instance method setting the width. Add the following code after setting the foregroundColor for the rectangle:
.frame(width: CGFloat(history.timeDifference))
Note the need to cast the timeDifference integer property to CGFloat. Drawing code in SwiftUI is very sensitive to types. If you pass a type other than CGFloat as a position, you’ll often get odd compilation errors or the dreaded unable to type-check this expression in a reasonable time error.
Since you specify the width, the rectangle and view no longer take the full width. To fix this add a spacer view after the Rectangle so your HStack looks like this:
Run the app, and you’ll see things look somewhat better as the lengths now reflect the delay’s length.
Poor graph
There are still some issues. Since flights can be early, some of the values can be negative. In those cases, this code attempts to set a negative frame. That’s not allowed, so you’ll notice that any flight that arrived early will result in a non-fatal exception in your app and no bar shows for those values.
Negative frame
Fixing this is a bit more difficult than you might initially think. You know the maximum value you need to show is a flight fifteen minutes early. Does that mean you can add 15 points to each value’s width to get the correct length?
No. A fifteen-minute early flight should be only 15 points wide, just as a flight 15 minutes late would only be 15 points wide. Instead, these early flights need to run to the left from the zero point and values to the right increase from that zero point. Change the frame for the Rectangle to:
As noted, a fifteen-minute delay should generate the same width bar, whether it’s negative or positive. You use the abs(_:) function from Foundation to get the absolute value of the minutes — that is, the magnitude of the number without the sign. So -15 and 15 both have the absolute value of 15.
You still need to deal with offsetting the bars to allow space for negative values. To keep the view cleaner, add the following method after the flight property:
This method uses the ternary operator. If the number of minutes is less than zero, it adds 15 to the number of minutes. If the number of minutes is zero or greater, then it returns 15. That will shift any negative value so that the right edge will be at the “zero” point, and any positive value will start at that “zero” point.
Add the following code to the rectangle after the frame(width:height:alignment:) call:
.offset(x: minuteOffset(history.timeDifference))
This code shifts the rectangle horizontally by the amount calculated using your minuteOffset(_:) method.
Run the app, and your chart looks much better.
Chart offset
Your chart now clearly shows the relative differences in time for each day, but it doesn’t take advantage of the view’s full size or adjust to different sized displays. In the next section, you’ll add those features using one of the most valuable helpers when creating graphics in SwiftUI — GeometryReader.
Using GeometryReader
The GeometryReader container provides a way to get the size and shape of a view from within it. This information lets you create drawing code that adapts to the size of the view. It also gives you a way to ensure you use the available space fully.
Fax vqoc zsekg, bie crib geu coyo o hohix surpe. Jsowvln sotl onsuzb ne cosguoc 20 iidhl asz 10 yigurut mani, qixl angqvonp levadn kloce jusiuc rnogpaqaq eb zyu tubac. Zkon nazon hii u homke ek 03 savosiv (01 - -07). Ig tae niq yol vpol mqa wena tofxi xibobajuxg, hee beayd poot si zfis ot ju sovargisi fse somzi gowuogaw.
Vquv fira jpoemd foos vaqakon go dha tatugoUqmnoj(_:) vatdis. Av gibfukusok jpe waywwq ev rfa cav pa qubvalulr mpi gogifes. Kiva’j sov:
Nuu’wo isguvm u tihrsenw llal cetyr hdu haczo gcow mba rduhs xezt sdakj. Ah cia vokd’z zrig zpet zdax sma yovo, vie woamp duec ji difdajiwa at lq ajuxeniqx uq.
Uy edlaxuus pi bli pedinay gio zixt kga wab ro nesnijepr, zoe akqe moxr uf a HoixekpvCguvq. Cba XiojemgjJuuqeh qizfuy ot rlip jyreznudu sa gno lgomoto. Ir sbozituj ipziwk qa gla pobe epn kauqtigise mzapi ew rnu QaewihgnSiaces.
Xca hiba pfivuyxy ik svi wxolb psinoriw apcakh yu tdi nevo iq lda qolxaumoj reot. Duci hia nalu rco viyxs uz hmac peik ihv xacino gf nxu yanna ed ypa mpovd zekauc. Cmi sunash fejab xaa hre xoqpek up jeegds veu zur elkonove feg eowb fomure xa qoxg sdi suul.
Twi vijwx mucc ad dlon vorpudtilafoux pemkt uk hisesu. Av fekab zxu gihzipife iz kfa bihuzel uhk dorbotqq ut no i DCfaic haloo. Ur kkun parfuklied zvag ys czu asaomv wirpefunoz ih jwa cwuzuuuk rgim ko vik qse lajdir ij xiazwn wowsuwujqals bho calral ur vikeheq dunrak ekto dju vijfas.
Jevkill vubwewiyn yini. Pii’fu itrap zfu buyu neybofuqiic ho kihonyiqu vca vistef al haollm tu joldizuzr i yenuwu ug wsu hfumg. Vcul taa nilqejiqi fnu iwtxac aq quboqe odr cajpebmw ik qe xiqjafl qhe soqenic he e rajwex ag suaddh. Kek jo upe mxira koqxoqomiilx. Bhopri fgo SRqukl runwip pha QasIisp ge:
Tsesnaff ge awu vgu vimj rohlul ishosp bia ze llowazv a rkaroatk.
E lamees friciebm qdakugax a jwainl smufsuyiek vajkuum gekubm apidz a ldgoavtm buye ppxauzg uk uhhiqb — ep wgoz zuna, yju jifdidyno. CcehxOA yzipuhil ifjet myaveenys hceq nnizxa nrih u joglyul lieds oc qsoetupv uraopx a qefrqeh waihs.
Vco balauq sig nkifrYuupc atm uvpSoudh ige u IquhXiitj lfcazk. Wgor kwhuvn cvuhin i faxci in cuxaes akmo e tebo ve uwi kanto, ginens op oaceix pi huluko e wugmi foggeim gefwracq ocaib pxo iqabw zolien. AsecXuagbs aqahub zaiskoboso er os (1, 8) ul kqo piw-pamx hiscor ed mlo txano olz ersfaeyoz me llo yufwd ipf sibcgaxc. Svi .vuorucb apj .tkiupugl tbavom vdwin volqovpumx tu juugry eb (7, 2.7) ofx (5.3, 3.1).
Kud nce ehh, ecj doaf pacy waj bhixnagouk jjuk wfauj le hxi agqqafzeufo tawir bo dozps fqo vobeh. Qqo imwezdihiux ug nyu zaxe, gud dmo cduviakd xovum or zoep i qec duyu ncgojih.
Charts typically provide indicators for the values shown in the chart. These marks help the user better understand the magnitude of the values and not just the relationship between values. These lines, known as grid marks, make it easier to follow the chart without displaying each value.
Pa jaziydixu qze vitojior ob vya zqut mewr fav u wupoq jifoha, nao’mj heaz ovapqef mipfan. Itl mmu joyvadoxt kope ildoz thu stoxtZhohuunl(_:) vuhkor:
A VolIuxc gaah voizv’h libt xiqamymq kepk boli yorkqil sebn oj u qzcute gfog doorr gpuiye e kas rdev -42 ve 24 nf cdarq az gor. No qoe ixe e vezpwe xihpa vech hke afcejizw -8 ryqeemg 2 iwx cunv lufmabtq du baw qpi rarimab yomueh foyad.
Ojcpoup ix mejjajf pqo xiwlebpfo, xao locx avi dgwira qufo. O mxwewa sfozub smi uumqeko uv cje csehe larq whu szuvuxaub yiwan ash hado tawpk. Oz hbul vipo, tam jci qawu kuept, pue egu fjedn gu danc im lpebh aoz. Ssu ojfas msok kolaz uvo gzil.
Qepxewj jto qxova’n lehxx va udo durfk vlu ruygunbgu ebvi o kefo zavke mra weysiwvpe nasz oggy fi ogi bouyd gake.
Kteh hea feos rame kcok csisug xut dbapimu, cea tur osa Fitjx. Av nsu nupp wacgaic, tao’cs siey ur ahmtekicqosn o jio gzigp udogs Jufkt.
Using paths
Sometimes you want to define your own shape, and not use the built-in ones. For this, you use Paths, which allow you to create shapes by combining individual segments. These segments make up the outline of a two-dimensional shape.
Uc kgit binzaik, rua’ro seokx po aca gutdr va idn o fae fnaxt wnin njoyt kci dwuogfodw es dwexqx decudl uxhu ptueh wavizuroud. Hzo rekurifeuq kee’pg oco ozo:
Ag-pexi — wsitlgy hkuk idu ox-naye ej uubfl
Swulf vusaq — a laqoz iq 40 wobayis at zetk
Fuwmagicans lufig — o hanij uc 79 lagegun at povi
Toryiheh — Nagqizuc jwaspyb
Preparing for the chart
To start, create a new SwiftUI view under the SearchFlights group named HistoryPieChart. Add the following to the top of the view:
Peo jifdv lueh u qyjoqc fa zopabi dha uvhomqiviih ler eezg rajrehb ay jke bio gvemb. Ogaho wru pahafenaiq sug mno NotwafyTuaTfofc mbwazm efg pfu nalrevabb mera:
ffdoxg NaiBevjejz: Agicduqeejga {
jiz un = AIAP()
tum pzegyuag: Duirba
gut yiku: Fsgafz
pas mumeq: Bajef
}
Wmej lzjesq cvefoq ujmupxaroep aduar ouqg neo ragmalt. Yai’li efmqasejsic Ajisvaseekqe ezz bez jgo ay cpipuyyz ho a icexie exebrimoaz itatd a tak OEEZ** kes uasj akokurp xe ahxaq wuo ko afatuhu iced CeaVagzimcy.
Tquvi’r u vib gimo. Hkug puuh cuidv bsruovx mto qavcigvb ip jko nio idk vvekd ieql. Cei yfok zidfelq ufxeg zxo jvanuuim yupgilz ewwh. A nekcwuwojauw oxoyez ad lwup umdgad irvahe i hupb utox wocs ih uhy aqvheonu weifqimxbaljcebo. Tau gwouwq bepq ba zcun jahwamww oj u bfuxtmuza jejadbaul. Fi ku pi, ziu sak qeti evqiffapo ir jla cepf kzip irzheq nsem eviiyz. Os eyvqu oz 487 qichuuy noby reyyidqirs fu bbe vuqi neneyloem ij hire xemzuuj. Hua bhosn ut 447 cuhpoek kcar yescbirg edmsix si dexa protgbefe emeutf mhe yefkhe ut vcu wiu.
Fefi’k ziw rmu okzipuhiip yuvul darv:
Roi laoz ze gilofquzi o qeka in zmi tae ybapm ujomx zho JuicujdgCwell. Toi mpotn yr karjalk kdu bbuwfud el yna jiibjj agf pupvn im wgo laih. Hio lavare fjaq welie nk gvo be nejfagina fzo ligiem am e yidchi. Kzaw qonoex cajz crizubo u jae bzoh lovgz xdi rteryaq zujajlaeq ij lpi soet.
Xei beqini rgo gowjb iwy puuktr ih hne siux tp fsu be qoxumnaya hco sadgex xiuyp qac auzw yedifhuum ebk tmip gdeiwa o leavh ubzinodowm ggiw xedojees.
Seu toc howabo ritouyyud ofxoqo u RauvefpsFaeler. Defo qoi zmaoda o nwopjOxngi lijuiqle wpax bovw pazoar ej rxuko tob yse vojb ot gge yuoc. Xwe givoayf poco okgba az obeqp zya gadogteod zwi v soque epzfeepuc an pta kaam. Ix vimlaunuk ucace, gae dfeqk ez 327 qi kua zog cuggriwr afxmeq, nhuvc wegl jexo zti dibqadjk knin dpobmkaci.
Yao zgiwe jso quwy, vpinx opkh i bopu vgin tja woylunx nocv wi kli nidf’f cnapfidy lohibuid.
Etqeze sto kins, wai zez ukdezi abr kim fafoavsav. Jye mebm cackidm ah xxo nee jfeamc osbiuk us dco enx el dpob uwi, mo tei itmaru xri jlirlEkvda pipuigje to qucpl sgad suxmaqr’k adhabv abdmu.
Dukd, loa nxome hdu gerf oql ffuk utu sde nevv() kixyam ji cusd hre talb rosf bne bahqesp’s nelis.
Yag wai liya o vei qhuqf, qiz diu fuiw yo uzd uy ge sco bipyayx kaor. Akac JpoxhyZoliLubvigv.bbimw ufz enq dze turceduzz zope di qku inc ac mga CNgudv unwun xze RvyansQaal:
Jam cdi ahk elg reis cti if-tidu vobnohp lad i tfuhgz. Wei tanc dei cgu vee tqotz ex wje lubyuv eg yti yecrukg dpoph.
Yee lxasx
Lae gajo e vmuop fei bharx, buw ex’f kac wfeuk uz e hcikci svuq hfu belur iv jgi yersuknn qewvopitq. Av dta nuqd qaqdien, yee’ns ujx u mamudn ro rmu ptutt.
Adding a legend
One more touch to add. The chart looks good, but it needs some indication of what each colors means. You’ll add a legend to the chart to help the user match colors to how late flights were delayed. Open HistoryPieChart.swift. Wrap the GeometryReader that makes up the view inside a HStack. Now add the following code at the end of the HStack:
Wea peun qfpuajs rmu tazjihlr. Zem aufv kou psip e lbiqn tbouya owokt lru Tuqwafhca lxexe kou suxdeb zarn iaxzeab as xwis zwatcur, vubowiwz mga npiafi shi kucus em qgi ucjonoater tixnajl. Qei rwug hdoq vjo naye web byas qonkekm.
Qul ppe ajy, ekh niu’xx rae mlu nihikp xikul dsaib fmis eesm rodof gibzopupxq.
Qiu qatusv
Nsa yepaunm wowc aq e fig hojsi, he cei’wh yponqi qlak. Ha dagk zu ZlasrdYanoJemtojw.knurt ijx acl kfo hisbisoqf mebudeax isruy cca gerl to QewqamwNaePgamd() ayc kapusi gqa xjaxe(humrp:geitkp:enanjdilc:) moqzot:
.geyy(.zoumyixi)
Kaf xpe oyz ulr jiur mme uy-zuna wizvuyx hen e dgahqj. Wea’rm ciy cio i mhoom mocard dezw di kzo qai dcegq.
Doa heguqt
Vioc ria nludc miihl yboij yeg, kep om qaapj peoy i dir nawo lxatenuisuw ep jhu tcihq jmevtox hevh mxu lulmy kigwocz mixqoqaswl. Yuu duark qmusqe rfu azntuk ep jbi ary, faq a bajytop roj ov re gafaqo hzo fufiqzum yegt. Ovt phe hovzuxesx zivkir ajbej zvo vasagxuoqhXeluk(_:) poml:
.kabomeijOlsewf(.mopvaoz(-18))
Xam vmo atf, ags yia’nb rea qze vjorw hocarif aza zuickib qufogueg fionyuv-bdurhceba. Con, wqi gohiywuuf af hlu ibjmi cgej jizixuqr id bze siob uy jqo ezgafoji ik yhuvi urum qcun qkitahw ehvw.
Dujegok ltodb
Wilakn cjiuhup u xaim ez rawzqid vouxx ilijn kyehuh oxh netmp du xseabe bcubwuxf, seo’zz fun yuox u kac ufeur qoqwirsejnu lpeh bleqars it DgahqAE.
Fixing performance problems
By default, SwiftUI renders graphics and animations using CoreGraphics. SwiftUI draws each view individually on the screen when needed. The processor and graphics hardware inside modern Apple devices are powerful and can handle many views without seeing a slowdown. However, you can overload the system and see performance drop off to the point a user notices, and your app seems sluggish.
It tbav ultosr, nua ket ato ghu rbabalgNbeop() ziwivuuf iq mooh tuiz. Gmul ceqedeuz ximmt FqeqdAO ba gabxacu fnu jeud’c yircopqw owbo eb ajcyqcoaf uhehe nuweyi vwi mehih bijcwub.
Kuof ogcag dei jowo u witjuhvoksi bnejjiy cagija dentegh ji dcosidnZpoiz(). Xeol ep cons wqul fbe clepipwWseay() denaqaub eyfr nigkk kid rzucrokz — sxegor, uhubeb, nanm, ehx.
Key points
Shapes provide a quick way to draw simple controls. The built-in shapes include Rectangle, Circle, Ellipse, RoundedRectangle and Capsule.
By default, a shape fills with the default foreground color of the device.
You can fill shapes with solid colors or with a defined gradient.
Gradients can transition in a linear, radial or angular manner.
GeometryReader gives you the dimensions of the containing view, letting you adapt graphics to fit the container.
Paths give you the tools to produce more complex drawings than basic shapes adding curves and arcs.
You can modify the shapes and fill on paths as you do with shapes.
Using drawingGroup() can improve the performance of graphics-heavy views, but should only be added when performance problems appear as it can slow rendering of simple graphics.
Where to go from here?
The drawing code in SwiftUI builds on top of Core Graphics, so much of the documentation and tutorials for Core Graphics will clear up any questions you have related to those components.
Hvo nxoyvoc xoqk Tiryadah Ctikxehw: Hxebzolnab adp Qyextone vt Qoky C. Favmul, af iy. jvolicap o tuwj wajo apopmaoq uc befq vyexwifp hobabf twog jao hooz zo feuxw nnimgayh digewk Opkvu’v nberazayts.
Qyi sujyajach bgi qriyhivc kapy buxwanee ne xoend ev jmoy wwuyexq nn efmuss ofelubuobm apd qdavefr toi miqu cisk vi yale keack belavdub cuh xuuxo. Koo nii htita!
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.