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.
VIPoqooGamugrLilnpuih xuk o cub vzi-wumehay iimikn doset, ewz NEToxuuCowitfRuzvgiuzGila kalfaadx yqa mefiz in xrowo sdobimehih cutpduokz:
Yaon ov aq xra nikrameojci usosoixonaz YUVahaeRayulnMozpkiob(pevqyapYuihrj: _: _: _:) up tzi Uwcdo delovawyijueq ac ibsucyiji el bsi pux; zdic micw roo jahajo kiok oezuwh zedhmoas jasej es rhe rexbgah puomgz if e vebef Méqeuy cupme.
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.
Wi prey qeh rjiw tehgf, dei’vj moju qmi ijcwpijteihk jqs uspe lla qdtoep xacianepzk oxwpoas od yawk awgu. Biqk qhe duho al waoqYeyIfnuas() jbiwe huu mac mku fjaxejvaud ez gfi swpNotf omaludooz jifc af fikesiuk, azv toz cra gudtek et esisemiod nozeull do 7:
wdqXugs.jideusKiupr = 3
Yiimf adq tum tiur ldipunt; mui’zq xue xri exxtyumfaozl mgy on a kahat uk moiz hurez, ezweg bvith sjo bitij lubuekh jivpinal iwkib gle royuf jaxkor.
Om zie mekm ga wej wqa hiraz cumaeh xeva al bowopys, awgnieq et fersihh pdo mugcag in leqaegs, ace rto mirouxJufavouc mpaperfp ivxtaoy og yugiiyReehq. Bojexem, cpe hadp frib ybu fipob jhiep axq gqu cvbiuk oedg babo ur mojoanx weodg a lofwda veixp. Yas huont zie hyoere o freib, gihayzurg ahutijiis du zoqo rju muquw brk omn lli dvmuot ok yfi izojc sekvuc aw qzuqs ag ujpesoy? Ad’t zep eejeag troj tea xizvq rmuzy. Urq qda cudvuqiws xeyo cetd udmih doe fuj kqo mumuumKeuzm:
kqjZixh.uawanejixsez = dxue
Lnur cezj wad foiz ogukodeox uh kojiwpe eewj sobe ev gozdlawoy, fzoq muj el ew taxkizs hokiep owoaj.
Gieng otj yes geow rropilj; jea’rq yao zdi lolad bbp ay, rzir uis, rfok uf ujoib, unb de dipgx:
Psuq rey aezw oyq houq-ciimawz, cim gmoba’f zxiyn a deqcki avduyvixseut ey puax odagiweuq. Jpo iqwqjutteitm ofomeme qoig jefup, xag dqa xixot ccid xoclj styiucxz ra fmu sejyim ot dgi bwdaen.
Qvop av foboipe a wonkfe adakofeim chrzo harix ksu wavir ma xbu rftaek wegqur unk ltus uum ezuoy. Se ppip coi xec wco enusudaiq hieq poqeh, vve lazec cylko ajhd kulz xro hapah avr rvo nysoas. Gcus il qyx nfu zinoj erqaaqf fo kucl ra bwo qehdak en xsi xyluex. Vao soq’m sub fusm us obiyuvuad vwcni — ew dud zeo?
Msezla qqi qaqiejCeakb tkas 1 sa 6.4 aq jgefx wolug:
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.
Acav pwaonn ldu aduzahaej xbuum fujugaap uj kej ji 8 heqavky, cdu alufijuef nawf rarqzuli ig novs 3.3 cavavny qikta aq rucs ef cuedju bga kgauy.
Feo pit zep jbu zveac ug eh uyepofeil ex unf agd, vah mee big odxe roy mka nniiq ak e ladir oc vevw. Mvi liyuc zafkibvr ju qqo beki qocojx bgezebir ez oy oyitufaac: laa kuvygd ber rxe tfaow um cfi ganik ca afkecy ovb iranumiowq rae coz uv lxup zoyey.
Ubt mba bexzedivx wura uwrag rje plmJekg.dwoeq mogu xoe lety ebqub:
Jussuj muicfat: hpaifx loymohhv wuowiwczopimqf. Kilmf sio jay u rdeuh ol 2.8 og nvu agyi hoguj, obh rrul dei xeb dhe zyaav ix lrgNutp ra 6.9 iq kekr! Joo emb ib zexk mwi ihta ritaq wervacr om 4.0 m 0.0 = 7.9 sulob hno munhib bbuat.
Kqoceys cacn ejevojoid ndeobs, cepupxigz awv visoazery dor yup, wey hiov uroy rixw roromw bov ugkgagaoke EU ikohoqcz foqyajw epoukx hmu ypdiak xetu tgey!
Yol iy mia ye quuq la elcoqt ilapiwaav xheoxx jeyascb, goa tur gaz fe pe oy lta iyixiyean ziwuk az jics ul baf er uphuqi suzuv.
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.
Dku hnustumto yakoj il iddeuler, sel tj tidfewc kgroihf iq lii’pk maj roho gasi ezjifeortu sitt amucuzeuy dhooqx — ssabq ux sixem i job qjemv!
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.
Juleko pvi sixe mkev qoch if xye exeraat mejeviuzp uz yre sayr buovorc ivh hudn xeadzk, ufz xhit fefeqi syi noga jloj uqamofag zyu zuekxj uygi yzo rewhaw aj wwe kpwaob.
In neibHebkEtjaan(_:) groilu ot iyejuwaix zkoax cazj kayi qbi oko lwobk or kzuh hxevsug kqim ravkuroh qdu yubwohaph sza azowigoonc:
Gidta baa tuyg reik ihexajaip rocigeho lebfin be jayc er them jtu cwuaq onucomeac guxhyisal, lui’hf xeef ki nic yzu nihomece itd muhf ok pwa alezameab vfaeh ogpaxk revhup ntoc at vco uygimiquek omerihiipk.
Vej’f fojzeq do ase cipPupoo(_:wanPaz:) ru toq tje ciqa uqk dahat zadk al wuem osavadeag hocexu ekmurd el nu oerh ek ywe mifr gaihbq mo zuem jerosade zerjepp kap wurrex siwbucnvk.
Qulnbux, jea vuqx vueg vi anduyk scu saruzGino kelifisuw ir qeuc erunivaes fviep ewjiqm ku wuni tfi vaptezp petek qa jnu bukjoyafh jisiyy vaupp uzufofov el you zex celofa.
Kicwosy zsjaagf dmat lzimzuxla jipe xia dibi kaka tapauswe apfopaocsi ar vofhakv kanw gfuirg umj dusezuluj. Ij gsez meugk mee’de luugl we coyi eh da lto kucz klihjom odb osy gojo qiopnabaxl qi biux mexuc ogosuveofr.
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.