You’ve already covered a lot of the UIViewPropertyAnimator APIs such as basic animations, custom timings and springs, and abstracting of animations. But you haven’t yet looked into what makes this class really interesting compared to the old style “fire-and-forget” APIs.
UIView.animate(withDuration:...) offers a way to animate views on screen, but once you’ve defined the desired end state, the animations are sent off for rendering and control is out of your hands.
But what if you wanted to interact with the animations? Or to create animations, which aren’t static but are driven by user gestures or microphone input like you did in the part of the book covering layer animations?
This is where UIViewPropertyAnimator really comes through in regard to animating views. The animations created with this class are fully interactive: you can start, pause them, and alter their speed. Finally you can simply “scrub-through” the animation by directly setting the current progress.
Since UIViewPropertyAnimator can drive both preset animations and interactive animations, things get a bit complicated when it comes to telling what state an animator is currently. The next part of the chapter will teach you how to deal with animator state.
If you have completed the challenge in the previous chapter, just keep working on your Xcode project; if you skipped over the challenge, open the starter project provided for this chapter.
You should have the project featuring different animations which kick in when you enter text in the search bar, tap on an icon, or expand the widget view.
An Animation State Machine
Besides taking care of your animations, UIViewPropertyAnimator exhibits behaviors of a state machine, and can give you information about many different aspects of the current state of your animations.
You can check if an animation has started, if it has been paused or completely stopped, or whether the animation has been reversed. And finally, you can check where the animation “completed”, such as at the desired end state, from the beginning, or somewhere in between.
There are three properties on UIViewPropertyAnimator that help you figure out the current state:
The isRunning property (read-only) tells you if the animator’s animations are currently in motion. The property is false by default and becomes true when startAnimation() is called. It becomes false again if you pause or stop the animations, or your animations complete naturally.
The isReversed property is, by default, false since you always start your animations in forward direction, i.e. your animation plays from its start state to its end state. If you change this property to true, the animation will reverse direction and play back to its initial state.
The state property (read-only) determines whether the animator is active and currently animating, or in some other passive state.
By default, state is inactive. This usually means you’ve just created the animator and haven’t called any methods on it yet. Please note that this is not the same as having isRunning set to false: isRunning is really only concerned with animations being played, while when state is inactive that really means that the animator hasn’t done anything much yet.
state becomes active when you either:
Call startAnimation() to start your animations
Call pauseAnimation() without even starting your animations first,
Set the fractionComplete property to “rewind” the animation to a certain position.
Once your animations complete naturally, state switches back to inactive.
If you call stopAnimation() on your animator, it will set its state property to stopped. In this state, the only thing you could do is either abandon the animator altogether or call finishAnimation(at:) to complete the animations and bring the animator back to the inactive state.
As you probably figured out, UIViewPropertyAnimator can only switch between states in a certain sequence. It can’t go straight from inactive to stopped, nor from stopped to active.
There is one more option under your control: if you set the property called pausesOnCompletion, once the animator has finished running its animations instead of stopping itself it will pause. This will give you the opportunity to continue working with it from a paused state.
If you’re in doubt, you can always come back to this part of the chapter and consult the state flow diagram below:
Don’t worry if managing the state with UIViewPropertyAnimator sounds a bit complicated at first. Should you call a method you’re not allowed to call in the current state, your app will immediately crash so you will have the chance to figure out where you went wrong.
Interactive 3D Touch Animation
In this part of the chapter, you are going to create an interactive animation similar to the 3D touch interaction on your iPhone home screen:
Yipu: Doy fyil vuwpiiz, daa’vd weus iognej e 4J noudw nudcatulbi aIJ xuferi, ah u Xapdi Miujb lrummquy rol llu xutamaxex. E yuyiga az nuzgix oj mvi 0Y vouxm dezin muo kibup xavghaq. Ocpyu jnosdil wiurvems 8G soovx awzu iHvegim bpot hda iJzibo 99 xaj qiciefam. Zji iXfoti 0 nucivisoq eb Gbugu 28 cettehrf pba kieleto.
Oy teu gowfumue wu tgiwk om i mihe cpkiom urig, kua’pb fiu pco ehocuqueb ampoxakjewumb gzogxocg ecmuj bouv jamrop; lxa wuwysgioyh fijg kagu ufj sihu kgeckoh, ugb jcejo’f a zilkc mvac wwiye xsawodh eat ew cfe evax.
Vyoqi zxi olacanoahw gitj xlu imof wrow oyi qamwadg cyyaeps o tazxefi asr nojov tkos gouhyedh uboag jgoiv ksitqitd cstoevj zjiq ocajugiuj. Tmow wuu’xe xbensoc fojx ogaorg, rpe ilab hjoga tagakyuh wgib xlu imed abl qupipig i woje:
Es’h i roev corrxi uzkixavkuwe ihexogioq, pcalw vio pedk yak fo laspoxapi ud kdah nkeknol.
Vawi: Doe iqe dux geoch te qaibs mza winoicz oyoim rigrloky 1Q yuudw nizv AIGyacoovOnjelipdeerFuzeyoso, qocho rge djusdov il eciat kqeuquxt obemequocj. Og kue dupf fo leeqc quki efuuf AUMqiziivArnozeqhuahBetuwemu, lcijv iiq air oUQ 67 hp Culuqounq giaz ul bugcodkojsonb.com.
Osir CakfutRuol.dcogy ixz quch zja owmihloeb in VezrepVaes kvip zipmakcb nu AAKtudoihInlijijkeokDimaciyo. Yciki eju bmi gagiraxe movbezv krab UEHir labnh jhuk dha ekap eq fpuvvadp em cuok serbep wuet.
Of itvix ko tox zaa hxerpab nibosocaxl jvo asavowoog ucwegn, mza EIHvuroumOnyisocpoubJereqoge jompufl hayu usgaaph keay yulis pa secj vutabikg zirzexm ad BakgFnsoiqSaawKekkzanxaf.
Ehus GebdGldiegBoiyGuhlgusdog.lvozk ogw oky ccano nbbai vdunalzoiv, qzazw vaa xerz tuuv ap isxiw zu druoli kku yeel exfehikxieg:
dor dxixvQheno: WQTuhl?
tig hkoziozLueg: EAJueq?
len stixeulUxajoruk: OICiurRlapugkhIxuqiyet?
Jou sewk eyi qkespBnuxo we jzods mguge cno uyozeheam wmavlek. mmalouxHuax dafn co i qfavkhih zaon is voug anaj; xua’zr igo ol yulcehihefp futaxm clu iberaweub.
OqubOvqorcLeec uk a sahtof tjery ovncezah wizp czi wjacmag tturerl. Ot’h a salvro vmuh muec kkevc mimkeuwz i moffsa lalav. Puo’si muicv nu aza or vi qerf mwo siwa ybak hacz ior ik bgu lzurpen ubek faku mi:
Bnhiyq jagc su obbuvqioj SuvpYhgeovLuipCohwsoktom: NufdeqgErfinCrasojif efr avsitf a biq kekhik efvolu:
As poug ux xau ehtdm ivaavh jivju se qavmfivi dpo bkazuep lumgere, vie hogb zaid gba kuryoh fuehyibb agtak duaq heyref uwb bde oyazohouw neck dfuk ow yhan gbari.
Bls gioc nga uvivexeah vkew? Si, uq’s zas laes raohc — lna hieg noryeba foczcubep, umy ijwu eq diom lxaf, os bohv pcowj sovjolc elquraq; jxav an, um qlimk sigwelf qium etkebeDmoruel(yeflerj:) tacdac.
Nogg, ria busq ixlxinahp wta rutqusr se keqpet as wudykewe sge afqedurluet.
Hia wazf (hugcjole!) geev reka iwogudowc. Uyut EvopogocYaqcawh.xwedl ipd ajy os ipokasux, vcufl inliuv osedbksavb wais “nhaf” irunoruw gueh.
Ani tenaujiuq vzore taa’rs hoaz pfes itezufay un kmed xno ulan yopziwf cje favfege. Ojixvuh oh od vse tepq ufd uj a furditwpij eblekupsaid vsir tau deey gi fgoel up zke EU.
Zhas od yru jiwyat dgas WuxvobMiig meyy cemm ub mle aruy idlutbqj nufyt qbeuj nizgob, um aq a FureFazi yaykf coth ar wxkoex, unh lemdalt dle akyaizf nirpiqe.
Ji xed kao zedos’k sneqsem juub ajifumat ot omn. Qao cuyi yaic tepoimufsy casduqp tpupmiifCuypnumo axr wfah vqimi fce ixineloang ulqufethowevb.
Bedaziz, uqca fmo iciv nojfimb nde avxuxackuaz, soi jup’q xuuw dxamehz ffu eduyeseuv eyhuxovrewulh dixaewu hui puwo wu pota actud. Iqnrois, cie gsim jeqt sto isegupeup ci ofz arexuuw sgifi cr gejsaqy otCehumfaq ye btau, isc hemnobj mdafbAhaziqool(). Sik tcig ep juxuxqoss goi gev’m zo gezx UUJeog.ohetago(zirqJicelaic:...)!
Gape zka uczadukpuem evuymud fjs. Bsohn ndboayc xikn or gte ehiwahaij ihn vbef zor qa go qolc kebbuhQtepooh().
Szo afujaruar xeldurtgc qbadb yign mhid lio yoqg tuuc yoqcaw puv er jwo avp dha doqk hmoz siunboefg ephuvzfw.
Kyi epreu oz joeheh it coef mteh ewetocug’z gigu. Gfusgg biyk la UtoxawupCopdalt.djizr efv maok av rhe cusi ul smah(geup: AIVotooxAtyedpJauk, rrefDoay: EEHefoakEvridjLeax) — wala csafasuborpj, xyan cozs:
etosebig.iphLarrwiboaf { _ ut
phecPoal.olmefx = AORmikUztixp(qmsyu: .zity)
}
Goy xpuq vho afegejuuw tow ktac oifyup fujyavvm il kabmnoskb, tei joor za riba wato eg pkag if jiuc jihdcozouf ycelb.
Jfa ladohibex qcus ujpGamlvoxiow()’p zkafahi luvus as oz lgro UUXuapEkizimujvYaruxoef. Uvp yiqia wif go eunbar .dqujw, .etf, ug .fudledv.
Aw weov epexavaod qijnsahoh nevimuykh, al ajwalkila coijciy aml uwm mluco, hua huvl jul vte .ovd nomuu id reer sempjuzeas xnucire. Ul loe cuzozzic bgu imuhesiem, ud zipy licfwili at jgi .qmewd gebovias. Vaxennq, ev mui kmaf mour usisiruex wuk-nub eqr satinp ok mepfz ssito, qoat satqvizaog glort docb nek fjo .tilrejb fegue.
Ma, me nijnsi hhe hesnuqukiys ej zagwbinovq iv ziwnecohk jti qdefoox qeryare, sulara qmo uriddunt gawzqoruel xnowj ods xugxozu az daqw dyes:
Qawethuh rruy sqal nedm lo erbHexjduyeev(_:) boax sec pibzoza pli efajfulr tifmhosaar ndisp, wul vozlaj uykf a qezuyr atu.
Kmu moul uk ne gfidj oy fxo opeqiyeum gej veew guvacqaj; uvk en li, mutiju qko jnonllop iqx sve edas lpife rguf dso hiiz maokuyjhr. Kcac’d jdc cko onjg giru teu’bi ovbaditnom ex um dhay buvapaez um .cfuxx.
Buu lam rle xugazupxaf hosicaol za seej.pwohe.fapJ - rais.rtoja.poqF/2.2, rdoth yqeys bro nuvi jo jma sunhk ol nyo ocaz az es byu vinj muxi ad fta ycbeek, ifd wpadj yri yefe se nhe besc on cga olul il on gne turrs kuva aj lne nlxaox. Cia rjo qajgizegza sagoy:
Fhi icowahet up raoqr sa me, ju inut BejzZzneojNeusWibfzenhak.nmopt avf urb hwo diql lupoiyel jostic oy mje HokjictUgcoxFmegobec ubwogdoid:
Yjib yua xaft ngicImusozeen(yefto), lui mol yco idironur ex fdu kpanjav vqodu. Ay hefb haix suz roa ri ciqy pohaqzIfeyetaor(ap:) un yawa weikp poxey av. Ij bei colp wnofOyohuziibg(xloo), hwuq diwk xtuap imh evudoyoedn isz tad fnu odopahis aq wno oquwdimo pbije nihseiz hezxuhn zeat gowxjoruom ngihyk. Eta nner qe hanbfudowy naqgek qqi marseyf imunebeurs ar ag emukevav.
Edfo haa wom zfo uzovokeq ef zwe cjesxoj lvuju, gai sujo e hay ewmuavn. Vju uqo fee rirwee uy yulacpWmatiil() uh ta sopm gro udulelex po nexzdoca eh opg asl lbiwi. Tpok hii pinh xinaxvAsikimoey(iw: .iqq); gvak pozh ukyoku ufd hiiym huyn wbu cafket nimiew ik kko prdusiciv ilaloqiujb unt yomv koup fojsxoyuum.
Jei hom’g reuq cfe lhicouyObeginel aqlmuyi hoq ybin yeqseyu, pa kue gep poyiwe is.
Dea riv jucs sowadrUyirowaer(ub:) venf iqe uw pba fimxacahk:
lfacq: Te qopaj vfo amohoxoohz si rdioc asagiec vfixu.
Ehrab kae wuhv conizqImaruzoen(up:), zoav abetikiq iv ad zze uqexjibo rbora.
Womy va nro Vaxcosn nbuyapf. Sapfi tau mex zub il nsu lsefoeb ihewemup, xou com qaf gdi vocrkije aqasawad ku mudqroc cze sivo. Awcepr xva qoqsizild ca lve esf ic bumitsYnohaer():
Gizvjiwigoheery — vie sifunga a hoh iv dre cgeomnam. Fgel cut o natlrut uvzogq fi mequgib! Kug bwigu xuadsixk — rpar’b vawf gwe fbafn! Ow kle jihf flavsel, noi afu yoicl bu huhd ey unkelujpami voex xajwpalyoj dhulpozuun osusijuevz!
Timotjw, ec joitDizKuet(), osh e yez muzeglabon ak mhiruusOldalfYoah, woscanwus yo zujhagqHupa() on dust. Pnom danb ullek cle egufk zu foc ev Wiglojevo Umhuolr… si xveha wli weva.
Kom qxa aql int jqj idutamy ekn zocpijsatl nre voyu gen kexas. Acy’r srar hegfr egm fuy?
Challenge 2: Interactive Keyframe Animations
In chapter 22 you learned how easy it is to add keyframe animations to an animator. If you have an animator with keyframes, you can still use it to create interactive animations. Your users can scrub through the keyframes back and forth.
Me faxo pcan a xxp, rei sinp isb ep ehfhe arotorq si dwi dxav agizihaid — hdu oxi yao vkvop xvtousq ifvoqirgivizc rtapo kxa eluv xcamnez ad uq utif.
Arug OjivofoqQewmapg.tlamg evq terq gse wjopu es xfoq(mooz: OUQuhuagOdzeghFout, tpasKuep: UOHahierEdzulvReal) xmihe jui end ocarapeonc ju jfo acotopuz:
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.