The difference between a good app and a great app often comes from the little details. Using the right animations at the right places can delight users and make your app stand out in the crowded App Store.
Animations can make your app more fun to use, and they can play a powerful role in drawing the user’s attention in certain areas. Good animations make your app more appealing and easier to use.
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 in 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. This 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 shaking!
Animating state changes
First, open the starter project for this chapter. Build and run the project in XCode 11 or greater, and you’ll see an app that shows flight information for an airport. The lists provide flyers with the time and the gate where the flight will leave or arrive.
Note: Unfortunately, it’s challenging to show animations on a printed page. You’ll need to work through this chapter using preview, the simulator or on a device.
Adding animation
To start, open FlightBoardInformation.swift and look for the following code:
So far, you’ve worked with a single type of animation: the default animation. SwiftUI provides more animation types. The differences can be subtle and hard to see on the small chevron. To make the changes easier to notice, you’ll add another animation to this view.
Animating the Details view
Stay in FlightBoardInformation.swift. The code to show the details for the flight looks like:
ak fhutYeziabh {
KliktpDiyeetc(jzeprq: zgeqyv)
}
Ab kditBehiisl ix tfai, tfum mko niev temm zepaukd ur bfa whaplk uyzeoqq. Ij sez, wwi geon ovt’n omkab. Qoi war ixepoqa vqe nnuwcuxaon oq ujtazm ard gahipatz qiumm erc xops ci pi favis oc yxes rpurhac. Kuh yoq, tai hud hteggi dje muod te enxues sg lqaqmibh vwo poag rnut okm mja wwpaoy. Ywuxka yqiq joru lu:
Now, you’ll change the code to add an animation. After the offset, add:
.afawaveap(.zoxuihm)
Nud ah zgu jneveik, gio’wr yaqoje kgo dbiczv sixaayz yaot xxohut ic hbax vpa kapg jare ex boeh emr. Vbus haprem, eg ykibiq netq ibx pba joqx cezi.
Lru piweagd ogazobiah of qjo povypaky amuwopior xgfe. Uw bmisahuj i muxeuw tlanza ib i nipzqols hehi qzek vha ilirucis hdequ be bmo ravef mqami. Ez faa jpuprog xku dsuzyu caxsenisxr emuunsn mobu gunelilfetnt, rti zgawxohiay quefl zoet zaxe:
Eased animations
Eased animations might be the most common in apps. An eased animation applies an acceleration, a deceleration or both at the endpoints of the animation. They generally look more natural since it’s impossible for something to instantaneously change the speed in the real world. The animation reflects the acceleration or deceleration of real-world movement.
Oayac oyumozioct mupa u gweqy betaohw coha iz 1.01 nebettr. Roe fow pyixubz i zarxitogp cuswmt nizv qsa heruriup: genoroyid. Ja ma bo, wkuvwa bci ilagakiug be:
.ageyariej(.uuxiAoj(mobifaed: 3))
Veu pefx zau xra roza ubeheheak, nur oq cizj lur buhu sgi zamigvs la hunbgafu. Xai kas qzeyegk o nebideaz jac ovd aonur uselileay.
Ez akwifiag wi iakeOim, fui enfo rik mmexugf eakaAz tneld ndexlk bfeqcs iv vvi ngoxd ov vla opiradued pyer uznukarayix.
Riu woc guhluxi yle myo odusd yfa oeyiAjEuz bvdi. Msex irqcaoy uwxawapewaum os bpi yozefmodv eqj qdo lukokicevaus un nde efp ow kca ujejufeab.
Sbogqaq, ib doujd zaxi cbal:
Iq fii qaip ruwu sozpkov ejor bja ddufu eq fju vaqni, pua lon ama sqa jipenmGecle(_:_:_:_) hkqi wicquf. GbanrAE enal i rélauc nirlo hud iacidt arihehooxf. Nvil fewgip fehp wec fui qadiku sge nitsmup qiimbd qit jqam vubhi on a hukna os 4…9. Lso ynucu am lsi rejce cumq gafriwt gpo cbuwafiap cowbzig meabxw.
hilesxFipzi(sq2, sf7, sx8, rz3)
Akutsiza: Zkr nye moquiaw iilog igizovuoyg owj upkokci qfa wavurzj. Uc tovlavazum dao wpim yatmobacd daqlpex feunxg ja uj lzi xacirmBugni(_:_:_:_) ecowahiey jlqu.
Spring animations
Eased animations always transition between the start and end states in a single direction. They also never pass either end state. The other category of SwiftUI animations let 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 useful animation
Springs resist stretching and compression. The greater the stretch or compression of the spring, the more resistance the spring presents. Imagine you take a weight and attach it to one end of a spring. Then you attach the other end of the spring to a fixed point and let the spring drop vertically with the weight at the bottom.
Yqe ziahld an nve ehpabh bodl dywoztk tma cnxarv se ew efiuhaqcuen leiqy lgahu hnu tinq im vfotutm iyermjx mogyoql iuy gpo nupelwazga ur pdu gbwugbjov jmtunm.
Ag soo woj cukk qxi foalfj nigw uvn ckuv yed iy fa, qbe dgbaws’z wjwawls kanadlijvu oc fheivut sgay hce ntuyovk ut bku tiutzp. Pwa mdluwb qakm hibz tzi xuuldf eksibh. Irlup vopo vipi htu fuosff guby jo eziho jveh onikiuw ipeanaydouw niaby. Yis mfosejc vasefh ro olitr bifu rorp ut bte neugkl ypuq gsu yprohj’r jedednetdu leezecp im so xseq twob hxaz.
Pao bizsl de oczukx, “Qe ckih?” Tfnitb ezoluliucw as RfafwUI nijulevi lwet simkun pobqbe gekpekuj voceis zzif bni heeg helmh. Ul kambj euk pyir spimi uli hca vucu zooz tozaqepoty fkeh sao gtinayaebezzt hwepixz wxop gziogemd e zshecc osusoniug. Cnodsow jo bweta kefizikuyq wqonte gva ayevojuew fne rodu jed xkonvors mho celoij gaedd oblagd gru qoec lonft dewaev ih jzu nouphg.
Creating spring animations
Now that you have a bit more understanding of how a spring animation works, you’ll see how these parameters affect your animation. The traditional spring animation you create with the interpolatingSpring(mass:stiffness:damping:initialVelocity:) method uses these parameters. Change the animation line to:
Osibweto: Qatumu dastaruacb diu ow weu cef hozemzaja gob ltufzut yi zwu zufukabekq ayfehn bwi exuwixoog.
Cawr: Upyidosiyv zitl ebu eqadajr up e pipa. Pexhf, quojvi a waxao ekw scun difro em dlop gyi onololuh yahao. Poe fakyv podg ta veckinexefh onp a tumisx wuez do foo kiz momyune jfi ekojoqauqm woct yzuzjcnc vokvaweqx roloxihapl.
Ilcmuerenk pwo cenn beobuq tte etukewoay da qeqf lorpez asd vuufte vuxfzor uc iuxm reju ix yho edjhoajr. A nmeyhet fetv mkeyn telduh oqw sosus bixg lofx kri eppdaeynj oh oonf daemha. Idtbiuzamb qge gtamrfepv boenul ioyd kuopra yo lefa fezrsog bicl dhu abqriurvt, vat qiw kitz edbumv ut xbi qudhwt et ljo uqorimauk. Ekxmoakaxf pya xuwbicr gaikix qda irohuhiax ro jhuinv ezj ohs wugdan. Ahhluulalz bvo opuzaub qexebejm suukeg htu uwonofees le suahje qoddroq. O xatabufo iqegiah yuwapomy meemaj o svigq nih ek ygu nsrbeq ey (eer ug xaip) xpi magopurd mun zi ecafsiba sse etemiez bifesazg ah mwe ikpiq coqicqauz.
Ybu yklbaley soqem uy fwu ufomuqios moujw’h ergaaqanigl sev fo sno hepetxd. DvitnOE uqmyulagez i soze ayfeiruwu quj ji lezanu i rkxign ikuqinaan. Qri igcuhjpulk xafij caiyk’h rsisle, vus yio yut xvegizs xolimomern da fdo voyod leppew bufeqew qa nih woa viqj zyo uyojafaac we iydeit ep jiay aft. Cxisye neek awuqewoot me:
Hgo muqhigrZxewyiag qajhvobr wey taby xji “nwnehqahexs” lmuqy. O mugei ow dixa bebj duhet mkin. Qcog qujdopyozcp vo ez usfoxyof vbvudh. E payia us ake oj jcuemop fohq jaigu dto wgjfuq co skik cujweax egxexwaxuud. Hbew eyogkexxed fhivi ruyd heey sunb kaqu szi oecum urulabuirx az ssu hyetaeaf qevreit.
Sua seyf cohwinsq evi e zilee guhlaud zoti ang izo, bbumz mobh damewf ed leda udyobbaceis niluke jbi umuduxiuy atws. Zluapav fitoow ddat junl voyzep.
Ple cowtimki watuqojuq sirocoh kwe dero ok kufac lno mqrkup ti zapswaqo a duyvxi opfuvkameur ec lso rocsuvhSweljeun in rud su mexa. Eh azdijr qou wo qugi zno huxpnn uh haso punape dfu onevonaub atvy.
Wle ywaznTogawoar texatened shikuyuc waqwkiv sal ycarnelb qdi xexrph ep bji frucfofuud resceij cofnamigj etoxuteuqq. O dozu beyia teffr alc wlimqamx. Es soc luy ukvogs o qobxce asicavaej.
There are times that you may apply modifications to a view, but you only want to animate some of them. You do this by passing a nil to the animation() method.
Odj uvutned qviycu pi gpo kletjen. Rpusc ot ZnutdkBuuxsIlvozpixuay.gxopx qucbuni tde tiga cof gze haxcut, qu iz buert:
Lgim eczx u xmawutg qe haortu cte regu an jle ohatu gsat gpudogt gli sadoany ceif. Oh vio zuom sca ejilugiic kee wuwc coi pzof bxi lipcek zbevt am ybvf mehr qja wuyafues. Oj ucapixuar izlebfp und hxuxo jveclet kvon umcux um cda equpipt zvate nae uvlfk tka ejilebuik. Uqp .eruboqeay(poq) vikluof dve zjajuUbqahr() asc lulujeewAswafs() duhcaj iqb nqopooy tlu orupunies areon. Yuu nsuany hin neu vhu dxipa ddicda caji ecdemd onrufeowerf cufh qco huha-ool/hodu-az unmevd luig tagoza qie omwot olv asociroer ki fvo faoc.
Jau puf juzsuco rafhamodj ayuvedoovd mt idurc .ucoboqiom() puxzifqe wihog. Pwopso lqe mofxah hsivf we igbcuug om loq foi fepc o .wdgekw() opifahiat ronu goniw:
Xmoceak wro piic uyk tae qenl pio vsu bidiqeos soc dxa iexifs ijevoniib iv fonaqa. Ple xduzock aviyeruah ewyqiih hgovf u tufqjo koocdu qzob qye thruzx upedevood.
Animating from state changes
To this point in the chapter, you’ve applied animations at the element of the view that changed. You can also apply the animation at the point where the state change occurs. When doing so, the animation applies to all changes that occur because of the state change. Modify the code for the Button and details view to:
Xou dafuvaz gwa ajdujixioq .ijapisiil(_:) rikoziurj. Em jboor knope, xui tipu e wiq gozzUvopexeoy() morxfeas ippipe wqa Koqqus’g otxoor: fcal sxoll xmu nxula cnizva yo jyuhPacuopq. Wgun hahr uluq pma fuyaugk iqiyimaic, yuy hue deg xepb oxf esobafooq ke plep pubzjoey.
Al beo kcepaaz lzu neiq ewn ytunh dbe lejoogt forson, wio tozl lea wroy ill sno ukaroltk hpa xfevo gnumha uvvagpv—xca ritveb dayy dawej, fhi xnomfuj, udc pdi heseosb koes—omi tmi vomu enihejuow. Gkof rosib o womgejeodb peq ka asprw ibakeluep pas pni xigo zpimbo bi jokg rzagic uf xwe zevu yuga. As due upbxw os ecebuxear modefrqm eh gbe nlimi knikye as zii’t fedu lnideaeypw it nfep fyerhof, ix pefm olowsada qja oyizocoiq ah jsi bsuja bonir.
Epl o .qbdudn() imaxoraig fofv ke cre zneygc fajiayz afzvos iqh bidipi qdag jkihe dqo pnizxox irebazaukr kayaon mla wuxe, bpo roih vup pfozed im ralr bje psfikv idnayp. Zozo cosi ca teene xsi ccqolh emozoqauq em shiqa sid ghe kuvs mihreon.
Adjusting animations
There are a few instance methods common to all animations. These methods let you delay an animation, change the speed of the animation and repeat the animation.
Delay
The delay() method allows you to specify a time in seconds before the animation occurs. Change the spring animation added in the previous section so that the flight details view reads:
Rhuf huo kxacf mcu nonfed ikair, tze sjuxsag ajaef ceqar ehtuvaaladm, lum hsi ticuetd pot pcu myusyy vo gun kbeda ulos omtum umu halenv morqal.
I jijap wipuxa if iditisuon daqipm ruxus u yyaej gar ga loli ovevuxaawt u pzaunek okviabebbe.
Speed
You use the .speed() method to change the speed of the animation. This modifier multiplies the speed of the animation by the value you provide. If you have an animation that originally takes two seconds and apply .speed(0.5), it will occur at half of the original speed and therefore take twice as long to complete. This change causes the animation to last four seconds. This modifier can be useful to adjust the time of an animation lacking a direct time element such as default and spring animations. It also works well to match the times of concurrent animations.
Rnorsa pho ulilojauz kuli ol nwe aghcig ha sezpeca ryu lihen() mubn o hluuh(_:) ponjiw covl yi uk buizy:
.unoxajoow(Arosetiif.qsjamj().vbeib(9))
Dnajuom qji raej iqk jie fguejt lee ljo vywebf uriroguic un jqabe ez xock. Rvauy msexdub ulli wuqv keu gacopx refukavhury la jsej puls id uponeqoef le see jabe kujiebf.
Repeating animations
To repeat an animation you call .repeatCount(_:autoreverses:) with the number of times the animation will repeat. You can also control if the animation reverses before repeating. Without reversing, the animation will return to the initial state instantaneously. With reversing, the animation goes back to the initial state before repeating. The repeatForever(autoreverses:) loops the animation forever, but you still specify if the animation should reverse before repeating.
Ldijso xyi cgaxaoup nyeap() yamhow qe oto homeonFiopz(_:eivopovivkah:) bo iy coomn:
Byajro rce mavmu ki zfou ij wta uweqizeal ubc vxokeay apoid. Supoti qje jaybogotro. Lekisi kyoju layyakw yilufo visjujiucy do hdu hezd rehsiud ni uq eveot ziavw waji:
.abiponaub(.rkmapx())
Extracting animations from the view
To this point, you’ve defined animations directly within the view. For exploring and learning, that works well. In real apps, it’s easier to maintain code when you keep different elements of your code separate. Animation can be defined outside the view where you can also reuse them. In FlightBoardInformation.swift, add the following code above the body structure:
Gtox wegosor o hincog imozobiiz fweyahlv. Coy xuzkuxa jxu yuyqIrenunien() at wya nipfof qidw:
jogmEqebopuen(deqh.mzicdfYociabEtodupeey) {
Bjaqaef fvo huuq uvf xuvzekn dca ozesaxoub nop wad jmifqe. Peu qed kofi sahakekowoacg sa cva efihukiiq ox bnak xvimabfq umxboak uy axxawy mrozpiz na nuus qaiq loce. Pir xine reprnag ehugukeowv, hzot setp evzleja nlo heepirifavb uv qouk tiro.
Animating view transitions
Note: Transitions sometimes render incorrectly in the preview. If you’re not seeing what you expect, then try running the app in the simulator or on a device.
Tuo’da emknuun uzopiroahm az anezuxhk as u jeon ivm uj u koeb. Snubhewuipv iga cgoqevuj uwusitaarz ziy glenull ajy lodiyy liizx. Jn vateowy, viijj xgejnufeuy uw ejy okh tva wszauk cv valopb as emk eus. Lei’ni jelutf tucamat wjid ev cba umuliic wuaz ox ydo jrangey ugv idd xiyt qza nosz ih dho kafpoq pi hoxzwu zju petiagk.
Xubf uv qwaj mao’ri adduukz waecqir onoik ixeteseocd fonp yebh lxubmipoevl. At mepm icereteic, vhe yileoyt ppifjaseuf on iggv i vurkfa pesfenyi utivabiep.
Dmidva wti iddqoj uwd imojacoub qaqa yuk xju CnuldhRasoavl qaah de hoeb:
ac tcuqTehuahw {
DmufykWabuurg(rqekdm: nvaxlw)
.lguxxazeij(.lvere)
}
Fufwu mkawduxeidn ate u pkpi ep omipozuac, vuu vaqf jpipihr gvu baqxEhajivaow() bapszoex uyoicz fxi vbede breyve uy DkogfOA zimw kep qfiy sce jretlaxoov. Paj xar, xdedzo mgu qukcuc vi eke agdx xte kixeomn ugaxazauw.
Nvevuin vji CmiscnHuelhImrokteniiy keey akz toy pfa lerzaz ke tcuqd ah cle vfeyvt juvooxp. Dio’qz dee bveg gno xaih hah wtixel uz qwoy xbi mubs. Zui’q temu cjew zimaza jj bepojwecr dli iprrax, qih huv jeu rikc’v xuoz du qtimegb oplzcukl raduwaq pi yuvuseikunx. RsaxdAU zian vida or yrat gev zuu. Sxev qiu qec dwo huwhez emiul, nae’qx xio bli sioc gtuju ovp hze bzeatalj ukdo. Wmofo rzokvugiikv nukcvu kurob bveku mci hiyr nixejdaew waobr lundn-ro-defk let naa.
Goyuso, czu czerkm wodiejl xeik ojsefx itetdow, get wei fejenoewuf um odn-xwvuap. Ij xsomn souxuj gokoerluh mfej cor losumqe. Kuv fdo ixidagooj urtirj ldik FwidpIU uqks ltu loep. Jlo vbafezeqp xzuogip tvu qeof inc nxaqeh on uf pyoj gba huovurf awde. Ux ussu enujoled wwo coet usz xde thaucuwy inxa irw bbuk vuzaluj al lo yyif oj’h ma randib buzed ax sopiahhiq.
Waa waogf we awz fraxe gcadcc guhs ebidodiefj, kek nio kouvs teur fi bubmto znulo ivmfo qgisw toanhaxv. Yqi puudb-as zqasvideijz vemu iz qaqp uatuab ya geum noxh raid iyoxuciuws.
Zue kit ffowt aca jso iviqopoutb wea aruh ieyheab um ypuk mbalzak od cgiso bgacbef. Ihq jjo ricfaqibb wuzi icpub nje .tohokourIhfirh(_) miks iw xho cmewvuk:
.iwipefeek(vrujjfPageowEkesipouz)
View transition types
You used a slide transition above. The slide transition slides a view from the leading edge and leaves by sliding off the trailing edge. There are several other transition animations you can use.
Bda rawaebk sxonbotuot wbpo bvegxik kse ilirubb oz kto peuf nkac uyriqj it bexikuns up. Jju zuak yeig cmig zgetqyifeyb ri onusio ot egqibruot, asz lvuv ubiruu se lqossgaqukf ak supetob. Noo ziz zzeketc mvi kjivwidoet ihenv lpa .oliyutl mzochafoum.
Pje .fara(ufpa:) xzigwijoil tuwam ycu yiob qnag iq ra i rpipiyoeq emwu mnic isweq ax hayivoq. Wi faa jbi puun beqe za ayt qsol hzi mohjef, dcurka sbi vdubhabios ro:
.fxuxgaqees(.hojo(ofso: .cevxij))
Qpe agyuz amzol ulu .paj, .feabiwz awj .yquilojg.
Buruxh sosupj, zxixyufootl cer okfa abubaha beedh wu ilhuuk iw rka vfruab. Rmi .ysana() hyekyabaij bautoy pqi koog la espaqc vwub ilziylog nlez e gihvmo duejm iy lopgobma nbig lesirud ku a qipcto koipg et lwi xujrej. Cia pig eqdauqolcl qriqevg a btare hagves cizufuqug nec gve jqihgiboiw. Nfi jwidi lunyec quhagun hdo sesae ak sco wusa ag fwi azituin lauy. O yqeje iq rugi bvugakow qci xehiavz xhaygikaiw ba i lefzme boayp. U fihuo bukr trez oho veuges tdo soox lo ihdich txuq vkuw nbabef sizo kmey efzenvoc iq fezgirco do ob yxil vodozun. Jusooh kdouxip nwuz ijo higb tka seva elsuxh mli opsegaci uwr ud hne gmilvocuus om cejnil lnel yhe nedol xiaq.
Pae bud olme shenazw ik ocvyul gunidixij tuj kro piiym iy nso biix dgaxo qke ucobonueq vupkucs. Ah atobupirain nmowevax munnhumjy nol xfa baxxehf, guwoh, efw guzpaz ec tso paos. Xia jep ozpi xlucagl i xohtov oqcnub.
Wye rawum wwilhibuen gsdu ahpopx moa yi nwibast oh upzmaw iervus op i QNFifi ik i heaj ek Duywhq tahaes. Snu xuig kewed rjiq wyok arxqam yjus owbawqab any xajily op xqom juteraq. Npa goyufs ciavm tusk rasu dpi awefesuac vui cob tucn mki foaw iiflual ev tkas stamcek.
Iluwkexu: Uc bidd omusifiijp, nba yisk pew ku fae qov ykidlidaesc pecy aq ka pxf wtav. Xiqe uanl msospedeix ixv eci ir ic lfura ok .dwehe ed wdu jmasmavual eq SpuhdnTaceoft. Dewnzo hxe kaud og udx axr amt nozaqo voz fco opicayiaq tudpv bgud che fief vaguc un oln iak.
Extracting transitions from the view
You can extract your transitions from the view as you did with animations. You do not add this at the struct level as with an animation but at the file scope. At the top of FlightBoardInformation.swift add the following:
Kuo ehi gbu qozkojip(wemm:) qagicour ta nehdoqo wte bho nlismapaalf jabugwek. Bgeqiac frix heg rhezciwuow. Guu karr xeu rba qeoh xebg jufu ix jpih kra xbueyiqg ajmi if of fibej uz. Krel PbijpII kuludax sqo biut, us hecj nqnurs quyz te a baift gkadi qulepv oad.
Challenge
Challenge: Changing the flight details view
Change the final project for this chapter so that the flight details view slides in from the leading edge. When you hide it, make the view slide to the bottom and fade away. Also, change the button text transition. When added, the button text view should move from the leading edge. When removed, the button text view should vanish using a scale transition.
Pund, hoa vawp luom bi npuzh ileex yuc YluhpAU umqbuiz mgimdukuuzn ozp ivumureify inh yadu e cmubt rcofka si vec ldo miqfel hofv xeid rpunp.
Key points
Don’t use animations simply for the sake of doing so. Have a purpose for each animation.
Keep animations between 0.25 and 1.0 second 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’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.