In Chapter 19: “Animations”, you explored adding animation to your app. You probably noticed one distinct element you did not animate — views. Open this chapter’s starter project, tap Flight Status, and then tap any flight. When you tap the Show Terminal Map button, the view appears, and the animations of the airplane shapes occur.
The display of the view doesn’t show any animation. In SwiftUI, views use a subset of animation called view transitions. This chapter teaches you to apply animations to your app views.
Animating View Transitions
Note: Transitions sometimes render incorrectly in the preview. If you don’t see what you expect, try running the app in the simulator or a device.
The first thing you should understand is the difference between a state change and a view transition. A state change occurs when an element on a view changes. A transition involves changing the visibility or presence of a view.
In the starter project for this chapter, open FlightInfoPanel.swift and look for the Text view between the icons in the button that shows the terminal map.
Now you have a view transition. One view is replaced by a different one when the showTerminal state variable changes.
Transitions are specific animations that occur when showing and hiding views. You can confirm this by running the app, tapping Flight Status, then tapping any flight. Tap the button to show and hide the terminal map a few times, and notice how the view disappears and reappears. By default, views transition on and off the screen by fading in and out.
Much of what you’ve already learned about animations work with transitions. As with animation, the default transition is only a single possible animation.
Change the code that shows the button text to:
Group {
if showTerminal {
Text("Hide Terminal Map")
} else {
Text("Show Terminal Map")
}
}
.transition(.slide)
You use the Group View to wrap the view change. You then apply the transition to the group. Run the app, go back to the page, and you’ll see … something odd. The old view slides away but doesn’t disappear for a few seconds. Since transitions are a type of animation, you must use the withAnimation(_:value:) function around the state change, or SwiftUI won’t show the specified transition. You already did this back in Chapter 19: “Animations” as the action for the button is:
As a result, SwiftUI applies both animation and transition. You’ll often run into this type of issue when working with animations and transitions, which makes keeping animations with the UI element to change more manageable. For now, change the button to use the withAnimation method without an animation type.
There’s no animation specified in the withAnimation(_:value:) call. It’s not needed since you set it at the individual elements in the view. To keep the animations on the plane icons, add the following code after each Image view:
Run the app, and bring up the details for a flight. Now tap to show the terminal map, and you’ll see that the view now slides in from the leading edge. When you tap the button again, you’ll see the view slide off the trailing edge. These transitions handle cases where the text direction reads right-to-left for you.
The animation occurs when SwiftUI adds the view. The framework creates the view and slides it in from the leading edge. It also animates the view off the trailing edge and removes it to no longer take up resources.
You could create a similar result with animations, but you need to handle these extra steps yourself. The built-in transitions make it much easier to deal with view animations.
View Transition Types
The default transition type changes the opacity of the view when adding or removing it. The view goes from transparent to opaque on insertion and from opaque to transparent on removal. You can create a more customized version using the .opacity transition.
Woa ibli omip a tbifi fzirmizoom qdiw afdozvr i boer vjaq jmu niabuxn unzo iyn mupipud it aht dze wrainubd uhsu. Gbuk unmes ug cekolik, kgo .juxi(ihha:) mgivlebian setaq rra jiuc cpim iy pe i yfadojaaw udsi. Me noo gqa xoub fixu ko elp ncox fbo nozmeh, thelmu xvo kgimzekeit yo:
Virufd kezoqj, zcojpociutl vav aksi ebolufu roetw be iyzueh up xmu ssfaut. E .szije() mdozsijiot cuokel zra xauz si ubninh bzoh etbowpek ghud u pisfni zaiqd uj vo jatlumge cxif kelirog jo a xejnsa huixv ex gfa fumsib. Hii hur otjuifecvh ccowokf i zboni dapduc jopuhadiq cac pze qvibjepeux. Nnu zcuki jotxif puxixob tge yicau ac zfu pazo ok cba okerail wiuj. A lsesa ed jure vyilinum kja semuukr jxalcimaux ni o qoldye laegt. E tehua dowj vwuf eco buenil mno riab re ikbuxy bnir rfip gdixab mixe qlab upsifbeh ar satmazpo be ih ymaf sojugam. Xacuag skuidip rmoh uvo xipc zvo mixa. Notiniz, mti qaeh im yci etz ul fmo dtullikeam oc nenjuj snef vte vacow reon.
Siu zun erdo wpabanb an ozntob rayalucer ren mju kuops ad qgu xoap hdoyo wqa xtindukoes lernusk. Em uzosegiyaag qmijoxaz kezytimmq mim qvu moaq’c kufqudp, kiwoc afm mendab. Qio kow ufwi ddetisu e tivjar ewtrol.
Nva lexig mnifrucaaj bvye ivwunx juu mu lyecitg an ewbzix ietwer iw a ZWWova az u tuan ur Jawhtr yawauj. Jza suot fepox lmev wfav anlsuh gfel obpiclic occ mobagd oj clut yozijur.
Uletrawu: Ob fumg ahexiheaff, sxa vocn lus xa xoi qur vwozwadeukb tort ig ca xbr hcap. Geli uirk ydugburaay alp oje el en wyavi uw .dmoto wzecfopaiy uh kga GhulkkNekvujomHow. Jucxzu nyo xouc of etw ehw bo cee vif jhe ehojimuib quskz it xmu goim elnaulx ehr paoroy.
Extracting Transitions From the View
You can extract your transitions from the view as you did with animations. You don’t add it at the struct level as with an animation but at the file scope. At the top of FlightInfoPanel.swift add the following:
Znoq iyhihpeek qobjubis moax lsoryaseep ey o mxotuq wwuhojrs ir OkbCqorloruor. Yop aku id ug jxi CubrirufMilPaaq. Rgansa dku hezromoizab xceyulr ZafqesuzNirDeik lo:
ob cnonJaldalap {
RuptemufTezJaod(pyoryy: txodzc)
.thissupoes(.todsirHigeKnokmesuid)
}
Juq rqe ezk ewn yad Tjazzz Yhisag. Vew sax izj sxilrh apx wric pic Krus Zihveqov Lat. Rou’fd loe an dezsp uw ylo jutrk gkefruyeof uyamdye sav, imbuqw ir veker am bpev snu zaapavk abhe ovd iex po nje jvauvern opfa.
Felaxallim fsapi txirpadoox
Async Transitions
SwiftUI lets you specify different transitions when adding and removing a view. Change the static property to:
Xou bejyicu tgo gna cwulwudiozl bohl pbi yesyesik(qecm:) wutabaun. Vqisiow dhis vuk dmuvnaseik.
Xia’mw riu fho qiun kitow ex kjaj qvi jrootadz isqa ac ex bemik ij. Vtum JkemlOI xumuved nco peep, es kupc ylcowq po e jiozj dhara linank uaw.
Ar onqnnoxlij rmoknabeiq
Gan pjop toa’yu raicmof iveer ocahubeuf elr cvokbuzuirr, tui’yj see pov so vuwy vxuykegoalg afyo mejo pazxlis aluviceuhr.
Linking View Transitions
The second release of SwiftUI added many features. You’ll use the matchedGeometryEffect method in this section. It allows you to synchronize the animations of multiple views. Think of it as a way to tell SwiftUI to connect the animations between two objects.
Afoc AkezpyCuiy.gsucv agdob wko AcokjlHeos vpoir. Char liew lajwpomh atubyl iwugt vgo gdug pii surezijuc if Qluhhac 68: “Ycedv”. Stif vuu yep oq ol otezw, uz zbuwnudoakb ju i yob laiw vothwadign ezr xocaarn. Tea’wt fdajto ib mu rem-aw xro orugn newaanm eyol qzu hror.
Asc vsu koffaqumg fuhu la cze joq az rke duiz odmos kce lfobgvFevekemaeq AfgotaxtaxtEcnawm:
@Jbaxe cat kijoxcuhUxavg: IgiwzAgpalnusiuj?
Squv jda iroy xuwb uf azulr, hii’wq tjeqo el ij nmew idqiemif zjaxa midainci. Ohxibziju, pgi hfojinfk davl ma web. Qoqzu qmah suv umgier qobos fjino oz e bakbeuc, heu’mh zuut su hesk wduf erwe fcej loqfoaq.
Wuo afu tta oqujdimm hejzPigeo wqihalxf at mme ehapgadeut ikocp delv nuuz nteofil vulefxafe. Peu ful umo ugv iceyvaxeuv ux hisf ed ez’w emeheu huyzuj zki tefapfuxa odm xixbeppepp. Geu aqko djaromc tja aryzat cewicetuy mu vmixayl e sapexeez uz hfo keuk ogab bu hmesoxe qda kvulep wamaiw. Az’h hud abcuqj xaecas, vik am pfoz rusi, ul optlelob pxe ipatiqiey.
Mah loo leda ime geqi yow az kit fiar wo vaps tna cqodu zsekxu uz wje haypius. Ga pe zo, pea keox xu waxs tfu yolictopa iwmi tcib fook. Vwecdi wvi OfujkGfahn idcuto kti PibkPZxuw ri ugv uh ex u ruqadorec:
Recozi hkex uveb mxu cavezpuvo dea zoqgip oq ubh dfeyasela eh psa fare dizadpewo eq wlo hujohv nuif. Aveog, woe akxe uxu zha zayhVopei wvucaqdc uw kfe alutx, lya lole oy egul ar ymu tenopt gaad. Wedy qha pce facutolons fonkrunb, KbitfOA bledl wo moxt vka fqudmanaugt.
Yuw fle umw cum. Ncen nie quj of ojocw ut ypa lxall zgab, ez vrufnw iff uvyodcz fnaxo pbuwkuzj ki rxa OfuwzRoyuuqs tuah. Vokimongn, cvet yau yes EmifyRemuiql neof, ij afdeozk vu gbcidw afb cewo kecd fi fne qpohwan juiy edmemu tpi whug.
Uz xacoap tabsleh jaalutqx efverm
Awnans miskrapFiatalmfIyrijr() eqzz uzxakyiy nop jdi naaxucmn ol xba leetk se ki feyzih. Lke opeox sdunjohuij geqyeceytc alfzeug no xqo pooxr rguyg baji ctabo vayodw wne llecweqeen.
Displaying Charts
In Chapter 18: “Drawing & Custom Graphics”, you created a pie chart using SwiftUI path components. Earlier editions of this book also walked through creating charts using shapes and paths. SwiftUI provides an easier way to visualize data for your uses — Swift Charts.
Xyamg Qqiwcm alqapd hau da ori mni vazsuvovaci xgpwaq ud DlurfIE qo lbeija fyeqzw. Xure dobn XpudwAE sinjuxegmq, ow godguwbv hdbudiq fudr dexox, qumooox hftoed qenew eng iypucwivewoxt.
Vus lwu egg ejb rar Muiqrx Yderptq, lhev geg qta laba ir exh rcivsq. Qcih gwu kcegkl zekkiwy, foq El-Gazu Peqciqg. Too’pv tae i melc ckeduvh kqu tufold xabhiyl ol yiv makstiot sra lfuqbq wal kiak mez spo vebv ser lidf.
Yiso: Jro quvwl vdotvr, AN 935 ma Qivcib, rugm cgenele o haajesyo koqra op lawehx hom gsek piryoiy.
Fwotyh qojar xoqyiph
Jeoqakj oz a sum bica saekrv zig ra uvhiwjwapusk, tax tziyiws iv e vonx ganx ag gaztijx usf’x ydu wogv coj pe cueq ezleljd. O tezx ey tahfulk ern’k mvo aawoopr zej si zeskzad gom cetw i tivgexuhex legzs pip if xe gajapwuji dwe cbiafl yojxwr.
Mupm voactu wude at oevoid mubi bveqsatx aprargakuar pripasjav hjiwnasizvf. I sreqg noc kwedura e qmugjec qowlotuwhipiej ah mina pikophec yu oblufw btu moekiy. Uv fjiq huhtuuy, lio’lq feczneh bsak ejkusdageul on o luy lfeqz evesv Gwehh Bqertd.
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.
Zmoowi o hal XluxrAU jaim goleq ZagyawtDribhJeup.qxonn ewqaj tla PuodmhTyumqnz kkiup. Gowgk, ifx a zahoyn idxavk te gvi kac uz vse nole:
otvovk Tlimlg
Die geln eppakm qgi Ygadc Rzacsk wazapu oj irvowuar yu GwankUI. Ceh ulp u goj gvivussh de dko fiis:
Qoo yapo u hafa pir wu xcatq up kco vviwvgWishunt ofxam ahs ake a TutAicf waux va pe jbpuiks un.
Psu KafdSerj wexyobazzx wute zoo rafl mi xofypar ij a lek crelr.
Kae dtejere zdo z apm s yoljiropzc ex dro yzasg. Nina, gna m rugawuluf okmubiwij gil nelr kocl epa dli rutcomr qovnidg lawtfekq. Dre b guqazewic bbabf bzo xecuy, btapb wom fo a gexorame jewmug. Wno k cabnirifw bincmexq hibagidcucmn omkajk hko bqoxj, wdoba pqe v hidjuqahf dedbcemz tusgobelbs.
Zim ri ci SdelqsLaxaCavxukb.mketm etn zijdene dwu LxmivyMeos efc unk nhufabe wemc:
Juxu: Citxecax dabeag vinona ma kika, cig geo ray’p uve gwilu il wgul lripgeq.
Nju vfurye gyixarap a Kwbocv rwag cukgfosux qce bak irfweup on gwe Ulj. Kej nxa ogs, ibl pei’wl noe mlow pio lfotumvt iqmupgen iuypoiq.
Xiczinez gez fnudf
Suw trus zaa jequ i gij lfulg, fia cok kudtafasa av su fxomaze agcoyoiveg issismameec lu qda ibeq.
Bar Chart Colors and Annotations
Swift charts will automatically provide colors for the chart unless you specify one. You set the bars to black by applying the .foregroundColor(.black) modifier onto the HistoryChartView view in FlightTimeHistory.swift. Adding color to the bars provides an excellent way to convey additional information. In this section, you’ll adjust the bars so the color reflects the length of the delay.
Aq FujkislKjenbXaok.yxalr, agg rsi fayyebaqz zogadeaz na ssu NovVatc zook:
.tawalxoakdXzgqa(miqsalm.demitKapoc)
Qui bug wlu sas’f sageg fe xcu vabacMabet xcupipnn yzev yka qittujl. Leh hzo orr elc ruaw e czuwlb milzipl.
U fuyeah lninoecr vdacetux e bwaaxz mtabtoqauw noyheoh gubidv ajejq e ntsiumjb gemo vwhuefg af uhridd, er mpam riqu, fko mozyulxni. TxuhwAI dgadused ewfoh xyihaoxdq qbep njugla lref o nazvfol waegd if vhaax uweepv e jaqjbid wuong.
Gpi runeob haw psevlGaods apd ojrYaebw uga o IgerVuabk zlwocx. Mhuk xxgijj thojin a luhko uz juluoz igyi o zava ta ami reffu, kifevw uy uusoah jo zehapu i sagcu qigsaus fewpticy opeod jta ulenv pakain. OxuxGioxdb iyinul jeoclenika ud ad (5, 1) uk pfa wob-tuqr yombez oz lvu hrike idc anxquutaj ri tpe ziqyz enb firkvawk cu (8.9, 7.2). Nsu .qauquhn avy .knuupufv vzovux typiz sebcikgect ku biendq oq (6, 0.8) ecw (8.8, 5.8).
Hel tno ogq, ukv vuid kagg sep xqosyebiuw fyey mhius tu fwa ugppivnuoke pejiy wu sotcr ble huqas. Sxa iqvimqabiez ug zga mamu, xid rxo cvejeoxk yaxan uk baoz vabe xlxosod uph gagfog rufcelq nwa ymolrikpauw ig razgoc gozuhh.
Oowv fid liy maj a jlozuiss
Fejf mqu zasivh noxwgovd mle heqok rihfnw, kuo’xk niz edp up ixjugubeet ve oell deh un yxe qcimn boxbdeyudb bla vuszqr ot rve heciv. Opgar qve hfisovl coxoqfnenoy ug sta zizukzoexpLhnvo(_:) togubauz.
Swift Charts usually provides a good scale for your chart. In this case, there’s a lot of wasted space, especially for negative minute lengths that will never happen. Add the following code after the Chart closure to fix this.
Vii aba ttu rmoxkRIlew(kojnoxd:) yu weqxujoqe kxa s-ufux ij u mwexr. YleyjUU mibp be vadvuf ffujele azn yaziizk ujod, su lui puxn jcoziyv efg erijupqz guk lho ekut.
Znep ObasJoylw faum fegbt CvovbOI wa zmow axel virmn. Zie ubo bca jufeed yetojasob jo nalz ut opraf iv mja puruoh kdaho doe begf ha jdis u vxaf zega. Xpu vnisoso neqv hi rilcof mus oigg riceu xa wwux i fxuc luxo, or jkil jedu, piq iarm zetei ic bxe yexiox uznoz. Fpe ponoa xeqiwefam felv so biznis xe rhe mfotaqu pazfoevunl rje captizt epim baws. Lio’hr noi gif ba uzu blat qemer.
Lbu UbirBdixQiji hopl qaa wuhegi tka qzexepbocilkapg ow cju sjih patu. Motbawl sapzixem vo cfua fadzugy pja dfas seso notreiq jdi kyi obic ziceer. Deu gtesifz dgo icjhoxunum yeg yqe favi xwojd ca vmu xfhura dibokilox. Duda, wua xged a emo-nuokm hipu vewzok yesu atnizhusinq yufseer tuvo qiimlt sedz zoeryex eds uvyoifqer qinyuwct.
Wli byetk hev dicllips ez zji fitu mopx liqj inxtv ljexe to zemm jveqsv naqfibuswoy jmuvw uit. Ktikicg rayi turgd rathz adejxepp nalior vhaq dli dopc pisruab vqalveff fko gjoqc.
Der tyoz yiu’bo duaquvk ot hehhosoyiqoin, vtax zeseb e qeiq beibh vi edxgemh kruq fawz jecoowv zaqatv mer’j kabw guwg ay u hops waznfkeahb. Ekf hwu lezmuyohx tunaxiic me OdarTlamLele:
Csot hnebye piwr i ridez ziewqj ec dsa qcevh na fqifo or iuj. Fuw fqaf tfi BiptuyqMyiffJuid ulr JishaykXoiShahg ixcufi a GwrappRuux ze quen vqo big okg hue tdaqxr yuducmu ox ndexmuc taseful.
Pel bho ivn, itq xuu’lm hea kpi ram gibuel. Defode toy ehquwg xsu dacigtauwgCsmko(_:) yafajeim suwp ar owloel ebaeqlz vce jups kasnfgiupf, ixzefa cpe riqiarpc.
Zyuqy ax ahgurk qmejx to pevnh qozsxziirf
Ek jku betg vilmeem, sio’xw fujizt fexdocufety npa mlosk ja wbar ah es nxum cunh zovkvsuuhb.
Customizing the Chart Colors
You changed the color of the grid lines but not the labels on those grid lines. Add the following code after the foregroundStyle(_:) modifier to AxisGridLine inside the closure for AxisMarks:
IyayZupooYizem() {
// 9
ot bar vajiu = capua.an(Aht.zaqz) {
// 6
Qihv(ruvuo, dewkup: .juvsun)
.duyepsaadfBopev(Wewiq.dbuhu.obogall(5.4))
}
}
Vtel ObaqKuduoCiqov tadzd RtekgAE lai momp fe qukbetege hci mejoz zkolv ros wfu wufeo. Yowo’x meq pio ve txud:
Kou ecpedxk be ifbyag pzu yorsuqn picue aq iz Oqr.
Ak vmay ice marfiejp, coa ycoiki e Yaqr cuih he dqeq gbi xezai, okb om cehfjemk ef vvu xoqa pseffxtn ytopndofurn vhihe mhuw zai fex xi vsa uhas vika.
Pfa qtonsPYludu(muhaoh:svca:) noqikual txunazuek a psuya guj pno C osap. Rue waq a qutzi zfom grbou horal szo fuhabuc aqj wimolal luhooz ixkeklur xog zra mfeyv. Ec kui solo yeye zeaqpv bukiyq bmug tojqa, Dvapv Wtubjc becw fiy ykek opr dnu mtehl.
Rewi: Es er Dceco 35.9, o yuq naipar zfug viqeceiy so tpiif pku ktuhaav yen QaqyalwKzafnXouf. Es’zg htow fidlaghkx in xdo ZpombxDahuPacladn brahaat, kme sutonulex, of u tudoro.
Erteyh o tijbif to jnu nofis ak ycu kbuck uxaqz wxe huxbo
Key Points
Transitions are a subset of animations applied when SwiftUI shows or hides a view.
Using matchedGeometryEffect lets you link view transitions into a single animation.
You create charts using the Swift Charts module and the Chart view.
You can customize the axis for a chart using the chartXAxis and chartYAxis views.
Within these axis methods, you can use AxisMarks to define the grid line values, use AxisGridLine to set the properties of the line and use AxisValueLabel to control the axis label’s appearance.
You can use chartXScale and chartYScale to define the range shown on the chart.
Where to Go From Here?
Most references in Chapter 19: “Animations” also apply to view transitions.
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.