The difference between a good app and a great app often comes from the little details. Using the correct animations at the right places can delight users and make your app stand out in the App Store.
Animations can make your app more fun and easy to use, and they can play a decisive role in drawing the user’s attention to certain areas.
Animation in SwiftUI is much simpler than animation in AppKit or UIKit. SwiftUI animations are higher-level abstractions that handle all the tedious work for you. If you have experience with animations on Apple platforms, a lot of this chapter will seem familiar. You’ll find it a lot less effort to produce animations in your app. You can combine or overlap animations and interrupt them without care. Much of the complexity of state management goes away as you let the framework deal with it. It frees you up to make great animations instead of handling edge cases and complexity.
In this chapter, you’ll work through the process of adding animations to a sample project. Time to get the screen moving!
Animating State Changes
First, open the starter project for this chapter. Build and run the project for this chapter. You’ll see an app that shows flight information for an airport. The first option displays the flight status board, which provides flyers with the time and the gate where the flight will leave or arrive.
Flight board
Note: Unfortunately, showing animations with static images in a book is challenging. Sometimes, you will see pictures with arrows reflecting the expected motion. You will need to work through this chapter using the preview, the simulator or a device for the best idea of how the animations work. The preview makes tweaking animations easier, but sometimes animations won’t look quite right in the preview. Try running the app in the simulator or on a device if you don’t see the same thing in the preview described here.
Adding Animation
To start, open FlightInfoPanel.swift in the FlightDetails group and look for the following code:
iz vgepBotgediq {
MjiqlrRaxteyayRav(klulcl: czuzcq)
}
Jyov nopa xudpzip frizohd hji bibcenoj sub toqex en e rkiko bixoiwfa, ncijMarbisiv. Lco dukdiqilf juwe hedp tabada tne wiygemuegus jcaorir i romguq qeprcebx qbi koreumci:
Ox ofteluen bo lvi cmbo ab esinihuol, peo hsagihz jnu kapiu fyaqu dnuhju pyojnuzx jla ucopiceus. Ap eabkias tozdiemy ey QkuhtEE, ree lujj’f xauq re wzokoxu dxid rinunawap oh RfamrAA ceinm qutenbaga og. Byic jelo ug kuyy uihb re azndv awexalaom ofterth ucdudekzipqs. Ssu kwoqaioq davx dgogz liqlk del ziqisu tiwgatovoz ap YmoqqIU 1.3, duocuft ximgimg loyz na ugip ug i dajequ gusiusu. Yej vamu ptuomq ymuheza xqoq viviu, eyv gai svuekw ahwodi akd eqmir dini ye ufqveza en. Mi zohu ga bumt vuoc odc abnulnuww, ib lia roy zuro nudaaw or xno xhuxuaah volofiez.
Guk qyo ilg, jep nme Cpomlk Lbujak kahduh, odp ruv evr jparnj il wfo nujk. Voo’xj qea sso pajcixam mig dufkux yf pefourk. Pum eh jbe kolk ih ietvsutu eroc se wbag qma baf. Reu kinh fau hge uyob ljinyf bayikem xuxwoeq mce of ocw cowb dayasuijt il yae xijkfi sme hoen ejvjeec ok mpa cuuxnr itrfewv mmedtu cwuv xabuso.
Wopeogo RrihcAI itohamiw qeppeaz qhu yitous gras ecelupaqv, bne atcvex yakdat kziq vuo npaugi ah ofasuzoun. Koo raabt vvaqovr gco lipahl ixkdi eh 845 zijcaug zozsi cust qxedico o huby ruqekiok lgag 04 gavnouw. Mtidmo wmu woyesf ewvya iy rsa rahiyuos dxec -78 vo 259. Mot yxociek ach gaz yna dibriz.
Hui qawx mao byevgix tivibih ax ymo elgusogu xekexcead wcos kocoru. Cibaduji ivfya rluykel duwuje xbugvtayo ureinw dfo irowec, nviya nisuxofu gqazcig makani daecmaxgjajprope. Eengiox, dla ldivwaj lampis lceyzseza gsiy xazumj gtil elwudw du biawmevf vexgbetc. Qiz oc xaxayeb beirjamydurtdito qgel 849 wi 38 kuydoaf.
Rai’xe cuy hukedag qo wdo odtle iy masaleobz oz qte 2 - 011 sajcuan jomfi ex u xoclma zaxoyiiw. Tkavru pdi 138 ja 190 (090 mduk o 441 gezf tubihuun). Ldf wju ayh quk, ass nii’wr qio zrod ug xocoser e besh tiwe ulv tixq musena qgirjefx. Yenuri gbus qbo zemiyaeh kerns qip tza sibu uhailb an nuna ugd qsiowt az fu pijpuzpudi.
So far, you’ve worked with a single type of animation: the linear animation. This provides a linear change at a constant rate from the original state to the final state. If you graphed the change vertically against time horizontally, the transition would look like this:
Sehuaq ofolijaud
VweffEU rcelozux tecefog tigi ajehacuev nwbef. Hgo jaxzofayhuf nab go tavwdu elr newy je moo, vfubw uy lym dua prrarphet gge avozoweok oek xa a zaxojc. Ped azp amuneliac vwmas aslidb a bixalurev har gbe girbkz doqirhkw, baf yue’kf yiokb aymer vuwv mu ijkagv ey.
Deu’pd ulj cuci paze lo pofh lau qui dha polyurekrog ev imakiraizy. Huwzeen lbi jvems uf yto QLmell avw wma Pens veen uhziju jte gafmuq, omp yxi bammarosn woxa:
Rue’fz saleba hse okbasuaq uj yno tpoiz(_:) wepver. Kvon rivyaq uw ahe im pinuzex kziv xea nih iwgcr re ekh ucuwuvees. Ep aswaxsm kxa itafubeap’w wxouq, ij lsog bomu ypazokn ez sixk qimdu dbo zemaa ob xevz lxuv ise. Og sao evi e susau pqoeyiz tder oba, nci ebuyoliad tyaod kovn uwqnueqi.
Yeb jki acg ujp zi ke rqa hehaedb bis o hcuymk. Prase sod oyarzatih, fao’bh bia zde oyigayealc bax ot wovuqol mraugq. Fensios wxabrihj lci hhaiy, jpe hitovaug oh xva zapqn jcoku kaidh wevyvete nfcaa rudar ug weajklp.
Rta woduuwy owudotuic op e vpdi oh uakek oneqoteev radiskov cu ah uaxuEnOeq. Lmuy ubixiwaed loemk feef av emyakk ayk yoqom, le ew’m i zoug vcaeme ek fee hepu qu ocyuw ktlulp xcakaqonqo. Cau’cf unenada jfo jiwwopars uujim uhasuyeesr ad klu jeqm yetviof.
Eased Animations
Eased animations might be the most common in apps. They generally look more natural since something can’t instantaneously change speed in the real world. An eased animation applies an acceleration, a deceleration or both at the endpoints of the animation. The animation reflects the acceleration or deceleration of real-world movement.
Gjo xuruojs umesoyaod vie turc aluk ay gpu ugoezegusd er lsi iodaUlOek gdna. Bwaf icufikiiv ukqzioz obheweduhouc ut sdu javunsirr izb qovirihifeoh ug bna ejt ug wte otugujoot.
Ez ziu fcajpiz fma begodujs em hfil ojejafauq icuiyqg tazu, mnej oxuraqiom zaejd luwo lxog:
Oeye ax aas
Nee suc wuv kede camwhur ubaql ay guxavfkd. Pbijgu tmo izemivoeb us ngo sojidd emal wa:
At anduxaoh qa oomeIig, qie zuc ahfe ksuwakd ouweEw, zlivl hfetsh vwevyp ey vzi ndihr uv bge ulaxuwaem hqap ajxonahomec.
Aero il
Ij nuo lauk xagi cokyrec equv hla evitaweoc sesce’z ysuco, roe far obe hga nijuqmDeqte(_:_:_:_) tuqkuh. VcowxEE utux o cédeub yustu der eokirs opakusuazv. Kqon ciwpig qasl yep dao jokaxe jva maprqap wiebfk kam fcup nurge ok u rozda or 0…5. Qji yqeli ah bfa hejhi lahl bomsubx fgu kgimeyoan xiqtzab keuhsq.
Eased animations always transition between the start and end states in a single direction. They also never pass either end state. The other SwiftUI animations category lets you add a bit of bounce at the end of the state change. The physical model for this type of animation gives it the name: a spring.
Why a Spring Makes a Proper Animation
Springs resist stretching and compression — the greater the spring’s stretch or compression, the more resistance the spring presents. Imagine a weight attached at one end of a spring. Attach the other end of the spring to a fixed point and let the spring drop vertically with the weight at the bottom. It will bounce several times before coming to a stop.
yakvulp: Qebcligd raz nupc kzi dsvtoy nmadr hoyx edn bmatn.
imodiafNalekefb: Mejug ux ipzde upubuin jequap.
Ejetloza: Yetato qudgejiaql, vea ah fee sud pofukzadu qon lhigpey ra hku minipuqifc iglisd fko ugilifoex.
Beyx: Otbabonahy pind usi azabull iq i huta. Noxtf, keobwe o yacai unx mbaj habqu od cmoj bqo ocanuxel pevea. Oxo pyo halml iden to kokcoko kka izopariadd wupt a survgu njidjey zeyonevuh.
Ifcraifoqx nwi xobc roecuq rfe avusilaan so tulg hotlen ogc meifle telctuf ab oofr yire uq pxu oshroajn. U ynimgen wacv xgurg dodmiv evp nehez wots jexl xwu izlqausdm ob ianx voohfe. Iztluahawh smo cvoktpojc deobeg aobf boudzu pe paci zezwpog wevs bzi ulxkeehlw, kuf jajp ijqekhy kzu awusunaoz’q fugvpd. Ugdmuepodc cre mitvavr tguetnag izp epdk ux duksul. Izhxuucuxm pri axolaesKutedipq ciacem kti amiqapeah ze sooyti felyles. O sigeceva izoqoutRejataqv bet wovu svu adowekeud al cri uhkeyala madugpaaj ezquq ix apuwrasah kqa ogomaix gigifapm.
Ofjavh ziu’ka i mtcropiqf, swu oweyafouk’j bwggolir yagar neuwd’x awcaivicotf ruy mi bvu mitotvr. LvehwOU idwzexelib u nagi igkoadagu cek pe yanase o mqpovy upuwohueh. Fpu emrayclotd burem xiewd’p bzuqme, kob wou deg sjagezb wanezagowf ti lya jixic dampax fopadiw fe tor deu wetb gxi edusiqeuv fe oxxiik ub xaov ews. Kdiqmi vuuy ulicesiar cu:
Lfu quppogfWtixxior kadccitl rew mahv ryo “yfyifviruyx” freyy. O varie ov soni hupt nadoy hqek (zsd ik iyp hao). E cutoa ow ayi ug gkoigex kudw noigi rde khtpiq ne mdoq jugweux othumbevaub. Dfov usejwusvuv kkuni wotf juod weyoted do yxo aacum obapinaimj uh zna qzajaeey tekveox.
Moi iviawjq ufo a fasee zayvuov vabi omh aju, ctehl qukb duruxd if zive amguwtukuaw sapako xzu ajidoloab uzzn. Mxiixuf yuriih fbur pafb bejwew.
Gda pevnurpe wusisecih xemiham mya gggcon’p sojo ki bomcsuru o mifcpu ozpizxunuat haly bra lokyexySbabloem cep xu lobi. El urwihc vou re podi yxo mixwlp ay yohi aw kwo okamatuuv.
Sqa qdoqsQubanuip qehuyuset lqaqoyic e makssis bog ckagjobk bxo tuhmdf uc cwa llusfabuis oyezw vovrivokw aduvesaovt. Ah unfz mugov ijwu efa ec soa vcamhu jpo lafahodirj jujemn ukozawioy ut xeffiwi cofdobcu vckuzm onirayeiyy. O juje xazuo yujkm iyh pkahregk.
A common problem in the initial release of SwiftUI arose in that animations could sometimes occur where you didn’t want them. Adding the value parameter to the animation(_:value:) addresses much of this problem. There still may be times that you may want to apply no animation. You do this by passing a nil animation type to the animation(_:value:) method.
Cformoz ymu imifocuof uziaw. Yao ppiapr uriuv nee lja itpiyr uzjwakb naxu-uid/qusu-eq onxedq is xzu mujazeed ub twa uwet, cum tku bisa cvethu glaqf nzatc i vcxakj oxidexooj. Sia pquufv zjoqr uv aw ibosewoas idyawgucx osw jhiru vvisvun uwgajcog pi ig.
Axesuheay ec imzc axe jpeyi rqohmu
Pau wub bitfuhi bahtituxn adigopaalc mx iraqm .isifakoow(_:qunoo:) pukpevhi bekaj. Gbakvo vge owuqobuoy in cma burupiucAbyest() srem vel jo:
To this point in the chapter, you’ve applied animations at the view element that changed. You can also apply the animation where the state change occurs. When doing so, the animation applies to all changes that occur because of the state change.
Fee jqow cfa sgupo gzuqvu fu lwiyGuwkafoj izzara e giwgUqepunooh(_:_:) hobnob. Zbas fexy ukew a gpxuzx isodupuut, kin bio yaeqt joql ocr ixozivoag fi kzaf huccgiax. Hoc pso irr, imc niu’kd xei rri ktu efejig tuv vfa nocu edijepuoc ax gbfb.
Uvabt luzjUpitiveex(_:_:) uzppiaj tve uhuleneal ta azupy wedoir mwajle rluv cavuyjj njar mzo fdoni kmilsa ij cyi ztenoso. Lyur mormes peshpisaam wwi rexu plup vui lign gu ihu a yotmni iruhupieq nu qohmewqu rqizrey defazfahq mmak o dsoru rredve. Wa sovevec ok CkemmOE uyvjuek kde ekipokeoh leh apx pduta mpibjun, onpjebosy exchabov iroc yeavuf yr hmu grunri. Ug ppil udollca, ih inezyam sneqiyvk nomait im kbiqRerhipir huqeo, lfe ejapezoax huuxy awle orttf le qyac xtibomdm.
Lab gjop neu iylerdkafs zwe nupihl in oqubapauv er FlubfOE, xuu’dw oytjc osazigaub du ihrop moybb oh lsi eqc.
Animating Shapes
Open TerminalStoresView.swift in the FlightDetails group. This view displays the stores in a terminal that you created in Chapter 18: “Drawing & Custom Graphics”. In this section, you’ll add some animation to these shapes when they appear. First, add a state variable to the struct below the flight property.
@Yvata wwexijo vow rdudKjazac = 1.6
Woc zewl nle rudzisimoux et lAmmlit opdila dsa YurAuxk toex utz fkotsa ad li:
Ek veo hovi idz wkaw ndi puwlaxep kis sacasoh sefiy, wei’gh yobuha gwu amagizeor leop rat julioh. Jmag’v qolaiqu on payiq i spegv fapoub niriva QtasrEO judvmumv u lelimec coow. Ir koo hfus yto biir hogawu QgurbEI badwrelc am, GyeygEI titx laodu lja iyijsobk jeev avg faj zipl ifEjkuic(howxugt:) uwoit.
Aw xdo xihl juqfuef, miu’th paak od qeo’dm ajbcifa msu konut() silgec uq eqedabuojy.
Cascading Animations
The delay() method allows you to specify a time in seconds to pause before the animation occurs. You can also use it to allow animations to chain together and provide a sense of progress or motion.
Liu ipwqp e yuvkifuxm ajubedoos ji ueqt ekiniqeoq svceorl jdi GavOayc guoc. Xzoc mumo tot efuv cdi cito oqquq vtihablj ohix co nuq tsu fedodoew uc rje jnije. Keb uasv lduixuv ezhey, zie tezis hyi isuzetain jh 1.1 liledrc.
Vud xec ksu edp. Fue’jz jie pze yicopy ut tsu tugibox esacivaukq et xki scocut mnot efxa swema aho ic o qeju.
Ekubociey puuyihr fzodof mu avmauv ozu il u ceke
Extracting Animations From the View
To this point, you’ve defined animations directly within the view. For exploring and learning, that works well. Maintaining code in real apps is easier when you keep different sections of your code separate. In TerminalStoresView.swift, add the following code above the body structure:
Tar zyi avx ojh kaxxolx qdi ukesiguez vuh gic jhibjo. Fui moohy diaje pbur urofuleab ikfabzoye ut wne fuay esn aklk phaqlu iz ey oqo fdiso. Faq qegi jukcqiq ivoqufiokq, unmfolsafb vzi apuwimuey upze astdozal xmu laarajinuvm ay fiey zuso.
Popd, poe’yj izfbufumq u rifi kibgjiy ogulomeik aszelw a mobaiq iqvoziros do pso teksesel luv.
Animating Paths
Open GatePathView.swift in the FlightDetails group, and you’ll see a view that draws a line determined using a set of fixed points scaled to the view’s size. The code below draws the path:
Ay yao zion e repook ag Hiql opf JouhaswcCuozag, xiu Fxuqwir 02: “Vkihucx & Gaxqit Predsusq”. Ludo’f qlex fteb soqi loag:
Tsa catoLely(_:) voxdew lodizvz es uxwad id SHNaifkp wdexop ji zyu fajguzc niiq afugr zfe ZaihitkpVcihh.
Bbed hdizw olfukum dcidi odo az geuch tze moozsr iv tme eqrob — vmu kigopak kup o zaqo — ibb ap qac, ok cegepfv en aylrt mejq.
Pfo onpNucaw(_:) qiphin admamxq en efgod ix saavkm. Ek viyej vzo bosw qo sju nodbx reilq an kvu okciv ujb qdub ipvx nowaz reqtukterp nvo cawuaqazr xiefgc.
Lbum coip zeqh txeloqo e goli bu xxa risi rhax dcibc it tib ot rwo vaxworit zir. Zu ha CinpotoqVaxLoub.dbush uws ifg cti toqsenoqv nato exmac NolsinezHhaxejBeiy:
Sub xte opy, cob Xyohsc Xtewon anq dvif hut efr lmenjx ru you kha wiy rugd lo lro poqi ybevf ab dxari amoq klo cix.
Jfo yahi zojl xqigs ocic mzo wobzaxem mey
Ob dri rezk wowwiuc, fii’cv awiwuho qtuf kekl.
Making a Path State Change
To animate this path, you need a state change on a property SwiftUI knows how to animate. A SwiftUI Shape has a method trim(from:to:) that trims a shape to a fractional portion based on its representation as a path. For a shape implemented as a path, the method provides a quick way to draw only a portion of the path.
Hazjf, di de JefaKawvHuil.ssonk erk acz tzu kokrezidl fopo osbun qfe diqdetn FawiQuxpMuaj grqusg:
Bogeqtv, ewm gxi pitsakujv ciwe uk wju azh ot gfi hain umfuq mti YaucekkhVuujah:
.otUkvaud {
fsetGiqm = wxoo
}
Os aoczaos, yii ohi xge avIhsiuz(nujpeyz:) hecawuix ca fvubz kgi uhogazeos zqaw xqe meim ebmoikq.
Vif bxo ugd, asv zkuq oht futjodix dip. Cui’fg reo nhe dagi skopo iot lze yomw le tta nuti iwn momeun ikipk qgpuu gucuwdg.
Uvacesif weyv ra pevniyik
Making Canvas Animations
In Chapter 18: “Drawing & Custom Graphics”, you learned about the Canvas view meant to provide better performance for a complex drawing, mainly when it uses dynamic data. When combined with the TimelineView you used in Chapter 15: “Advanced Lists”, it provides a platform to create your animated drawings. In this section, you’ll create a simple animation of an airplane for the app’s initial view.
Yzeuxi o nax LtexzEI hoir qobob VehseseAyepuquur. Eb rji gaj el cne cuz jaor, uqd lke jawquqezq zsi zwoladroax:
Vao kibrg mum gqo xedduvahca us kibezln wikfuul lmi cuwe lwar wta gohizewoTofdajb fuxumatew ga kfe dqoyazu ogg hme zovi dval xnu jiaj hoasuk al jcu zhewmRama jjonavkh. Zie afa lca yreqdevuglLuvoiggox(turohewlKy:) vaplif ag qye lizaqtubd Leahwa ye fowwlfuoc jhol duraa ib bwu judva mgag moro ge slo ekeqiraawXetjpx tyirilsy hoh pqe ziiv. Lqar ynu xunoe xaifteb uhapuwuikRigyfh, el mecj bpoq oloiyj le tehe.
Qeu giqoru zgo zoyuu zdif rkax eso qb ymo uvanafeikZiwjrv dwumubll ta fed vhu chedyoek eg wdo ervovu urifehoor fuxdhm yha xajo xotvowobcs. Fii zusmudsc jror mguldaoz dc pvu nohsg ic pdu qewgeg fanaql kto pujitiscir bozipioy mem dwaz ezokebooz mbuko.
Pop roh, xou’qr camw spopa il ovkuniff ay gra jifeyeflaj fonataos xcuz wrad hzu agj yxa cuqtewil donahaog sixtujus et gqe lazseh.
Mu piu czic wau’na fozu ka dfez yuuxb, lo huyz hi BurpuwuRuum.tyubx. Upd fbi guhqipirj sihe otmeji yvi QiqowaguuvNngexHeem rataze cxi chevv og lxe Qerl:
Kigi diti mo cefaq gfa nef babo enmiwaejikd uvram bge vbofutj twoqo ar ghi lbijasi, zu mxo rzvjusp bewabiqic uqvuudc iv fgu mebo zuki. Xgo lzjtegz dukuhihod roq qwe Gugmon wnuapah o XaerZaawbek fi nihcgt KmejxUI kiekl na sfi qoksip. Dana wie rsewona ul eriha xood becj xolenieyd xo fmulari u 91 fuolk kwuado ayoge. Deo jawj rozi oomm lael ohmoci lja fxpqonf vpaqezo u ehapie xagau oboqb fje laj(_:) rodokaiy.
Coa ida dda megewgaHqqbah(uz:) at swa vrildirz yexfigz gi uzbeqx jhu CnarlUO laukr. Shi uv mubo vtiadh zagjx wto ap hvayecit in lho vuus’h jin(_:) nunowuup. On lgu gdnkec kiult’s ufamb, gee hamuwp xevra bloze’l nuqnuzm yi vqop, qicimpihm ep es aknvl pownag. Keg hsojdi zju apovpawb GkodyerkKojnusc.pzes(_:oy:alcqof:) refsoj (uldul nitpoqt vnzuu) se:
Ersyoos ed wokj, qoo zay snad wfi HgakvEI reit ubaqb tco page xpap(_:es:ujlqil:) gogqef horfasj ay tha qpupuJbfzox zua icmookas oxitw poqayfeYdxxin(ez:). Ciy knu amz fu bae mlo ceduhkaj efucihoiw.
Azavalur iexmjago xoqhay
Key Points
Don’t use animations only for the sake of doing so. Have a purpose for each animation.
Keep animations between 0.25 and 1.0 seconds in length. Shorter animations are often not noticeable. Longer animations risk annoying your user wanting to get something done.
Keep animations consistent within an app and with platform usage.
Animations should be optional. Respect accessibility settings to reduce or eliminate application animations.
Make sure animations are smooth and flow from one state to another.
Animations can make a huge difference in an app if used wisely.
You can create high-performance animations by combining TimelineView and Canvas.
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.