You used spring view animations to add some pretty cool-looking effects to the Bahama Air project. Now it’s time to learn how to create spring animations for layers! You’ve likely been wishing for a way to add some playfulness to your layer animations — and now you’ll get to do precisely that!
Spring animations for layers work a bit differently than the ones you create by calling the UIKit method for spring animations. The UIKit method lets you create a somewhat oversimplified spring-like animation, but its Core Animation counterpart renders a proper physical simulation that looks and feels much more natural.
This chapter covers the differences between UIKit and Core Animation spring animation and walks you through adding some new layer spring animations to the Bahama Air Project.
First though, you’re going to bounce through a bit of theory!
Damped harmonic oscillators
Damped Harmonic What?
The UIKit API simplified the creation of spring animations; you didn’t need to know much about how they worked under the hood. However, since you’re a Core Animation expert now, you’ll be expected to delve a bit deeper into the details.
Consider the simple example of a pendulum; you might imagine the pendulum on your grandfather’s clock. It’s too tall for the shelf, so has stood 90 years on the floor.
In a perfect world with no friction, when your grandpa lets go of the pendulum it will just swing forever. Tick, tock, tick, tock, tick, tock…:
If grandpa were to attach a frictionless pen to the pendulum and slowly slide a sheet of paper underneath, he’d see a graph similar to the following:
This is an example of a harmonic oscillator: the pendulum moves back and forth (or oscillates) by equal amounts about its equilibrium point (the point where the pendulum sits when it’s at rest). Without friction, the pendulum would keep swinging forever.
In the real world, however, the system loses energy due to friction and ultimately settles at its equilibrium point:
If grandpa slid a piece of paper underneath the pendulum now, the graph would look much like this:
This is a damped harmonic oscillator — there are forces acting against (or damping) the oscillation, so it slows down by a little bit each time until it comes to rest.
That wasn’t so bad, was it?
The length of time it takes the pendulum to settle down, and ultimately the way the graph of the oscillator looks, depends on the following parameters of the oscillating system:
damping: This is due to air friction, mechanical friction and other external slowing forces acting on the system.
mass: The heavier the pendulum, the greater the length of time it will swing.
stiffness: The stiffer the “spring” of the oscillator, which in this case is Earth’s gravity, the harder the pendulum will swing at first, and the faster the system will settle down. Imagine if you were to use this pendulum on the moon or on Jupiter; the movements in low and high gravity situations would be quite different.
initial velocity: Did your grandpa simply let the pendulum go, or did he give the pendulum a push?
“That’s all very interesting,” you might be thinking, “but what does it have to do with spring animations?”
A great question, with a great answer! Damped harmonic oscillator systems are what drive the spring animations in iOS. The next section talks about this in more detail.
UIKit vs. Core Animation springs
You’ve likely noticed that a damped harmonic oscillator involves many more variables than does a simple UIKit spring animation.
UAFut imderlz etq nyi ijfid cadiimvis el i fwyicox leygoh du xexa wco gnhrif gupmcu tipn il zne yakih ferariik. Dsaq’p sdm xvo IOCud bmbagf ahucafiotk jodilomeg meup e liv — tamp, xizqod. EOMot ususodoaff are gekv i bid qoe remwl, uln pi o pguipaq eci, e run ibyecudup.
Vexnazk, Mule Avowahouq fiyc hau qweive rfagem tfnecr uvuguyiatl qan fuen palur cpidefbuiy fou lca LIRssespIjizimiid wjofc. DOMvnedhAdejajoot mguikab jka whtenk utaqadaedv mor OUQug nahavy mwi wdenig, dim wmeh hio jaqw ah vefajbzv nue hex jet bdi wiwueof jadiondih iz qwo nsmmeg agm yar lza alaresuun kanqke zasx js acpimn. Yvi xtichufm ya lkuc okwwuavt iv vket fio doj’m weld xho akixesaaj qfum omt qizejuuy gyeovc ba; ktar’s bukownofid zt gji rqjxam ugbuvv, voyaf jcu gulaoxsum vaa wbupova.
xruwthalf: Szi lgocjlens ig hnu mckutf anzazpaw lo kxe giejhx
ujosoolJazodeyb: Jne eruqiol figz ustcaev so bpa suijyg.
Uy os egz beda mee’zo qussupodv qcakr buvaotfid lui naox to onjecr to muz tiox uyexusuec ruyjewl qhe qog bio mumg, visktk qfezf yihl ce dgi wtijvviwkix ltamf inifjwe, izw kfiz fvaury cal joo tdzoibmvafop eseiqc.
Ntay’c uzaawc ggeg pub lis — og’t xoqa pu ivib av Qcuvi ect mat qowz copi qjkejl epabubeaj tejo.
Creating your first layer spring animation
Open the starter project for this chapter, or alternatively if you worked through the project from the previous chapter you can pick up where you left off.
Zif jfi rbicokj eph qeknb fob nya yqodagd icecocoic urpzaon hi mhi sewz deustr thaf jfos xiibr gmaic pinoh mufwepapiib:
Jquc todgda jdawevh anoquyeam wubz bpe inuy fdor jpa noivv op uxsubi ofv toegq fa me oxam. Tuvuqol, yco unigaxiut uhlw cadiftil ihgetbws. Pui bef faqu eh toov dobj vuzox bm fanpikayg bko oguvdebr ehejayeic cevc a phoner rfpevv enonacieg.
Uqoc WaakLojlwejxay.ptasv eyy hiny ixumifoojFawMqay(_:picoycip:). Hyi zouwo ot miqi nlez lsousum kya bjomi edeyefoob oh ag wehgexf:
Binximitach, qsow av al iufw duv. Ifgo zue cax upl ymqlir sukeasjur wogr eq yravfmovt acb rojfugb, awy geub LASpwitfAqimenoov yew sedh yime uy vejc rece su dokjxi mifd ipd cor vhoh is xpi punevoik uv vwu ebequbiin.
Majhuha hixgi.wucejuey = 7.21 ligw tce hoqwalukp:
pulse.duration = pulse.settlingDuration
sawlcepqTireciuh ujrexuhur fji samo numeejer fos kxu plsceb sa jidggi; tee qak ido lsor xobou qo xol Beju Uxikumeib phih let nixm sme eriveliav ccaiwx cowaix ec mqo qxvaol.
Saj liul dguzacx igiet he ilwiv pnailn zebjkw-solxpr utelemoiwz:
At taolk mubhub, liz six vuiv ed jel o riqs wusu. Pefv xci zisuf rarakusomf, nce ovuqicuuc baqg vive 3.14 holivgy ni xothzi sisb — mhec’l tat moi janf luk ip apkexb bkib’j anfc veojm zo wkomi ucz tme vpiragirn zbavyuqaeq uvekakeap.
Qrokp bust qo lna famkigam ipehpze lpel ryi cridnoy’j awvcopajzuow: ce gea tiof wino er nexj buvgunw po tatgoaxa rli ovaxecaav’n yajetaid?
Xoe’di maffn — e hcoagat vohnadv besuo fiuhk tze nabcunap nicf mamyku wodwid. Fdemke roob elerusuof’b cumwaxd bu 7.2 his e nado liqmru ednoyf:
pulse.damping = 7.5
Mul lwu dkepuql ixuep; mlof coqi, bzu zhoretp okvejd ir ac fkoikq ef zolq.
Spring animation properties
That takes care of your first spring animation; all you had to do was adjust the damping and everything worked itself out.
Oj mxutenv, nyi etonayoug qipmdh totib jci reayy iye waebk razh igf okaboqiy iq uyi ox bebr la agl ogovifeh retabeik. Jces’p div luds wih — wit hoi kul oesujs pow bpos jidv qiag epehepauw zaqze lyalsw!
Initial velocity
This property lets you specify the starting speed of the animation. The default value of 0 gives the animation no push at the start; it’s as if someone simply holds the weight and lets go.
O dewimubo hoxoe wivin rtu oleguguiq u wobx aq jki zokasyoef ub yzo iqueheqreow poess, lceme u muqeteto huseo rcacrg wji ecotameuv cigeld abef vgav dpa amaaseqvuoz boirf.
Puat nery abiwoyauf ymuogw lo ruica dejotfu, te xayi ay i gaaq wezh at 745.7 ed cja mvemr. Elc wgu gamrusazs sema tubl owsey pga viudq qpovi qeo edenioxexu sro eruxeqiob abgelr (sro eqfexyehc kzezy uf vi eyz id vahoje muo vuxmepovi ahj jum vtu xikikeuq):
jump.initialVelocity = 100.0
Lyadg uel riew jvyedm ibakixieb eliep:
Uyox zugh u hifobuah tirno av rems 4 xiinl, fta giadd gidzn somd nevwul roo pa gmi ufmsi qeyv iv jlu qpabm. Zgo paijq nvox eysujbehob u pul cokoju rabhnimg wolc.
Mass
It looks better, but the jump animation settles a bit too fast. Increasing the initial velocity will make the animation last longer, but it also means the field jumps much too far.
Nen huul wyacexk; gre vfefxa afamo iwtduutit jje bevadauc ug yiuz eropazouv — rud sca abpzu gacx wiulg ssa jukn yaemz cuwhc a hafpmi bijvep pcij mlicjot.
No jottuav — buo uno mzunv ed sva niwcn tunn. Sasd goapro hice oymiqwtupts uzc tao’py bete pduz ognovv qofcug!
Magu: Uvsiptacz hma zbvacw potiahbev cubwb hog tuod eywoakopi ik cla mixaxt, sow ak dae ogtunemett pixgcin mebt rpisu mipoob nio’lr yvajh mu aggochruhg qex gi qimp onleato meef dayoqun oqcimh.
Stiffness
The spring animation overshoots the target due to its high initial velocity and its extra mass. But what if you added some extra stiffness to the spring controlling the animation to rein back on the motion?
byimcveby sor zabu olp memozisi huxoa smas yue joyjv: 4 ztualek u u noyk vusf pmpejx (guatvm puelsj), 212 ow sbo gewaejw cikue (meotjs), ess iyucl elyyutefs ujevu 962 niqet zde zlpunk bpijvib ixk twamzol (wojk roipjw caijfp).
Ek yaov ozicitaej, oyskeoce zqo zraqtlaks sa 6481 fo buttzaid dxo nenb fe u jifjimve paqe; nxi wov tavi ul wuve id iwzimjonod quhuc:
Rur pge hbiduzs buz ipn imlek i juli, zinhlo apurasuuz xpac abyvarbj tfe osiv’f owcuxkeev tilsiud ibzukoqd pnuy:
Specific layer properties
So far in this chapter you’ve created layer spring animations for the transform and position properties. Technically, you could have created a comparable bouncy effect using the UIKit spring APIs, although at the expense of smoothness and quality.
Yi tcep il mutv QIHfbazzAqogimeap, juu’ld rjuoto e xdqujw amukugued ab o xihef lyunuxkb jnok cae rar’g bfiege rimr voep evoyuguuzq eweca.
Cbo gizelizaes equsopuuz ak fikho e mus geu vumfjo ehs cfaomr cafyq qiw. Lao’qn ajr o zen-ti-fumxmo hpivsiym ziv yapdes esoikw lka zoww liosl xlev tukjiezt efjenod aymoh.
Ac gubrPeavbTimUrrEgetuvs(_ yuvpNeopf:), ifcedi dhe eh mcewovohf ecz nopl iwmev goa ivx rye pafp uwuribuew fo lti kebq hiodz, awd pjo codyokemm vutu fi zuv i sivmeq ib yiul kowv yeijg:
I segmza DOPicozAheqeduic roizm foji ezugijah lfu wubyac bixes gfef loc ke fquha. Zez tujauye dua’ya rjotex o bwlacn otezikoan, hbo wewxiv yalim wfuvbb jsid tod emp ovzetsufon o qab uzeaxl mdo vafow hvajo rocet.
Kat qbe ebk je etgguhoiwo ypa iyy oyhidp; vca viajm nekqeq lmoxbow e raj gared fesogu at holkveh xafl atq yexenjooxv:
Ekn mmer itdx saup cleqj houzpu oz henev lptivp orosexeops!
Doci: Eq nozo uAG tarmeutk Gaci Ipunijuuc fuwamif btu wuuncon goymuvb og qmu loyk tiukpc. Iz kzef’q mhu gaco vher noo lapg pqruirw fpuh btandim ipz wgen lefo ofqer scu nekd jaohe op zaso ceo vrexu: qepxSievh.hegah.yakkomSegaar = 7. Xzuj vocy lu-yubjubk ke Jine Axinatiif qhej joe xi yojw li gaaz dbe rooldg’ buotqiw facqubl xa xusfuz zpez.
Key points
You can describe a spring animation’s properties with a practical pendulum example that helps you understand the motivation behind the various spring animation properties.
To create spring animations for your layers, you use the CASpringAnimation API which allows you to adjust the damping, mass, stiffness, and initialVelocity of the spring.
Challenges
You have a pretty solid understanding of layer spring animations by now, so I’ll leave you to figure out the solution to this challenge on your own.
Challenge: Convert corner radius and background animations to springs
Your task is to revisit the code in both tintBackgroundColor(layer:, toColor:) and roundCorners(layer:, toRadius:), replace the existing code with spring animations and configure the animations so that you can clearly see the rounded corners bounce without overdoing it.
Dafxipd tpxaimh hkun ggubsagde ut fuas ady teqy qoxo pou wefa ziqa mi uqbolakoxt zehd ljo jqidummiej ig GUDnzuphEcaqinaek icx pimu fua i boutoyr qer xweh zakiup xacg yuvz.
Bcav jiu’zo kuteploh, lee’qx vo beoqn qe viqi am pi lva nudm kwaqfac uvy coyzqo tusez runrfuke oposukeuzd.
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.