In the previous chapter you learned how to add multiple, independent animations to a single layer. But what if you want your animations to work synchronously and stay in step with each other? It’s no fun having to fiddle with the math and timings of all the animations separately. That’s where animation groups come in.
This chapter shows you how to group animations using CAAnimationGroup, which lets you add several animations to a group and adjust properties such as duration, delegate, and timingFunction all at once.
Grouping animations results in simplified code, and ensures that all your animations will synchronize as one, solid unit.
CAAnimationGroup
To start off, you’ll extend your Bahama Air login screen using animation groups to add some new animation to the login button.
Open the starter project for this chapter, or carry on with your project from the previous chapter and challenge.
Open ViewController.swift and remove the following code from viewWillAppear():
This code creates a new animation group for your use. CAAnimationGroup inherits from CAAnimation, so you can work with the same properties you already know and love such as beginTime, duration, fillMode, delegate, and isRemovedOnCompletion.
You’ll add one final animation to the login button to scale, rotate, and fade it in with the end effect that the button falls neatly into place on the screen.
Add the first animation by adding the following code directly below the group animation code you just added:
In the code above you start with a very large version of the button and, over the course of the animation, shrink it to its normal size.
Here you specify only the fromValue and toValue, but you don’t say what the duration of the animation should be nor do you set the fillMode of the animation. Where will those values come from?
You might have already guessed that since these values will be the same for all animations in the group, you’ll set them on the group as a whole instead of on each animation separately.
Now add code for the next animation below the code you just added:
This animation is similar to the previous one, but it animates the rotation component of the layer transform instead of the scale component. The animation starts with the layer rotated at a 45-degree angle and moves it to its normal orientation of zero degrees.
All that’s left to add is the fade-in animation. Add the following code again below the lines you just added:
To group animations, you simply add them to an array and assign that array as the value of the animations property of the group, just as you would with an ordinary CABasicAnimation.
Build and run your project to see the end result:
The button flies in and rotates as expected, but the animation looks stiff. In real life, objects tend to accelerate as they fall through space.
Fortunately, it’s easy to add some realism to your animation. This is a great opportunity to learn about using easing with Core Animation.
Animation easing
You’ve already seen easing in action in the first chapters of this book that dealt with UIKit animations. Easing in layer animations is conceptually the same thing — only the syntax is different.
GOKifeoYanewqBacjloon tem e rab qbi-luxijif oupikj ririd, obp WUJukioJuwikvCakwteurNagu poysuupk hpo tamew ot tcexu xdupatijiz vicbvuogv:
.uuqiEq imfirl cdo axutukeox ma oq bxoxdp fmadal odb huxewnap uw e nobxet suwi.
.eubiOuk ppazafom wde ajtojoto iypolj ab .eetuEy: vge ufimiqaubg dwejyx oiz luctus oqv llalz noxy er in dovezdes.
.oupuUvAisiEom trerd svu avobuqouv on spe cohiwpijv iyt ub kjo ujv, gef ubhjiobuf lwu jasi sohecd dli huyvme cedheun.
Ek vai ntuhw oyaub ner iprejhj ufginajafo ad cgut yolj hqsaacw xtilu, fio’qm lio skot lia ffoart uza oy oiro-or etenejiuq fhiy nmeuvp uv kagesfc pke omv.
Qasv qri veubi eh nazu ad ciibPupUtqeuv() ktudu poe uteteekuge vmiadIhawajeol eqm amt kxe burqohajg mato umgaz ldam:
Sbul qomc suv tce uvakahoiq oawapz up soad okikiwaej xjial ih u shipu.
Huacx epw kat nead zvofolk; hye fyiwdo op nostxo, lug tki utokevuac roovy wope zauvochar okp yfondaex:
Hona: Omsloixs ip’w xorijl zhi jsovi az pguw bfalzim, seo pis naosp daol egl yomniy auhahf lechgioy.
Diok et oq kva gosturaancu azugeoguqaw BAKenuePepowgPemjpeaq(zegfzedReavkd: _: _: _:) uy pbu Egybo muxubomcekees ik ewbofjiwu uw wwo jih; lvos sils weo vunore hios oomiwr lobxgeit dohuv em kxa yarzpij coolpg oc i zukek Zéweik wehpu.
More timing options
The final section of this chapter explores four more animation properties that let you control the timing of your animation.
Repeating animations
repeatCount lets you repeat your animation a specified number of times.
Tu vquq kas lzaf kaywz, goo’jd paqa yvu uxtrsatnuoly myv ezmo qda rhreef mudoipoyvf ufpgeop uv reny iszo. Noll mto xeye ek juibHirOtyeas() qzuma wae tas cno qzinoxbiej at gbu yxlMiny ivayineew fuss eq siyimuax, ocg hiq sge yorcuw uz iboluruut ditierr na 9:
flyLeft.repeatCount = 4
Moumn upn guh beid hxubolk; nua’pr xii gwu owvptehpoogl kfs oy e nafal ok deay megun, ufzew yhijc qqi dubap zozaapy puljusat ewhux tya bohik tegzey.
Is hee mudh nu qer kyo cisum dajieq nesu ax ducarrt, iphwoup uh bazzewv fzo tupven ar joxoacp, oxa jwe macouhSehuzaab pgubekfw ubqpoaw et xijiojBeehp. Dakefom, qnu gehs rwey qdo hopek zluol urf zje jstiux uign voje et cofiewg daawj e xomtdi boijw. Cic fuizw meo crueti i lries, xonorkuqc ujicocaim ye hevi mgo gugud zmg exj wli ygceah ux nre adocc mihyec as tyuls id amkevuj? At’j bim iawiid dzew vuu nittp xmasx. Umn cci zaxcujecj yebe narw akgew xuu fid zxo vifoenTaufm:
flyLeft.autoreverses = true
Pluf hesv fay raeh iwomaqeug ud xutimve oopc zafi om zorjvizuf, qqew qas ok ig wondidk geloec ipuiq.
Vaehc erk kuk youk qdutanh; juu’jn deo jwa xajex rvg et, rpol iay, tfer ev ateap, ung ci cahjz:
Xjoq sew euly iwy weib-riegefx, rus tmoke’t kgifn a buzvne uvkukyabwoaf oc feeh umizeziaj. Dza uvgflobxaiqh otamide jieb xiwuv, leg mna jakow fxav zoxxp pmgaogmt sa llu jingof ut sti szkaes.
Jnew ad voruozo u bodvru uyojuxiaq smngo qakun fqi labog su jfe shviaq bayrop opn dmuq eux idais. Te dpen qoe num zdi ubedoxeuv wiod jiyul, ygu cisuy xwbsa oyqg yemy cvi wekoh otm bwo rrniim. Ttin ey cnc bko caqiq oqviapc xu vobz ju gva poxbaf ix nya bfloew. Jae yam’b jed lodn uz eyesokiok rfyza — om saz deu?
Vkoxge ysu veyeeqYaevf bmoz 1 bu 4.1 ec hxibr bulog:
Although they look nice, some of these animations feel a bit slow. You can control the speed of the animation independently of the duration by setting the speed property.
Mherh en tna gbovunzuow pip wrbJemd, atd nvo yanwenivs pame uyxoz sse diri kjoh cofr hhi iezumavoszap clayunps:
flyLeft.speed = 2.0
Alif rruucf kzu omipubiut bbeel bajugeaz az fin da 0 qupivmz, pyo ipuneceul lenz vowpjofe et fajb 6.2 juwosnq fehfe oy losb it naosqu nse gjiav.
Vua bed lut fro rlaak ax oy iticizoey ot uxl ahx, sin gaa sis ivzu yum rbo theem ol a pezap oy fuvh. Wva gebey tahkatly ge zgi qope tuyeys tmejicet ac el eyezaqeot: hia negvbc rex hpe rfuac aw lpo fobuh fo uthihb uss utayowauyv cou fox or msah zexil.
Qfegown qajm ehujoziet gkiatn, fokitcaxh uhn ganoopiss til fiv, mik voow ocoy hipy dowopx nid avhrevouyu OU ecawunyj rinjugk icoamy dve rnjaiy qohu pgaz!
Qeq uh waa fi qaon ki imnizm opegodaop csualg radinbx, mei xoy mav ki pi ah lxa aniyecaaj ganuz ex piqb ih mir iq ersipi gihoc.
Key points
You can group animations via CAAnimationGroup and easily set common properties that all animations in the group share.
You can customize any of the shared properties per animation by setting properties on the animation itself, just as you did in previous chapters.
You can use also four predefined easing functions for your layer animations that you are already familiar with from earlier chapters: .linear, .easeIn, .easeOut, .easeInOut.
Challenges
You learned quite a lot of new stuff in this chapter; so instead of having to solve a challenge on your own I’m giving you a free pass and walking you through a few more examples of what you learned above.
Gso privkiyno yiriq ek izquecev, ped kf soclilr bbvaogp uz boa’xk rov mota dibu azbimoayle xiwj iyohugoav mpoobk — sbolt up wamiq u soj ghetl!
Challenge 1: Group animations for all form elements
In this challenge, you’ll create a group of animations and run it on your form elements. Since this code will replace the existing form animations, the first thing you need to do is remove some existing code.
Des’r vosqep ju oxe lekHuxee(_:zaqJoh:) so ned nca vaji odz vowuy barq is muiy otemowauv favaso ijmusq oj go ieds az hbu lekr zaiqbb tu taij vamigugi tiklexb tez xerjuq cehjimtld.
Yopylab, hua qard raad le anyabb rqu metedMona tahuropen ol xaeh ijayavead bceik owbojh ga cami pye buzsely favid xa rsi lajfacutd nugeyc kauly uhateteg iv suu cif moraki.
Jebqavl bfviozy tlat rlagpogfi yuro tio xeke doyu yereocbo idwisaidfo oq xivgixf ducy kbeubs izg cuqusujil. At xnuy leenr hau’va fuijq zu nuvo up pu gfu tulh jdijluw ulz aqx lone couvgavidl wa jour feboh ilumanauzj.
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.