In the previous chapter, you learned how to use Auto Layout to create a responsive user interface for your Packing List project. You’ll take it up a notch in this chapter and add a number of bouncy animations to your app. You’ve learned that in order for Auto Layout to work properly, you can’t fiddle directly with the view’s frame or center properties. Instead, you have to work with the layout constraints to create your desired animations.
So far you’ve seen how to animate view properties: you can animate numeric properties, such as alpha, from one float value to another. Instances of CGPoint, like in the case of the center property, can be modified progressively until the center value reaches the target position. Naturally, your next question would be “That’s great — but how do I animate a constraint?”
Animating constraints is no more difficult than animating properties; it’s just a little different. Usually you simply replace an existing constraint with a new one and let Auto Layout animate the UI between the two states.
The sole exception is when you only need to change a single property of the constraint, such as constant, in the constraint’s equation. In that case, you simply modify the constraint directly in code and animate the change.
In this chapter, you’ll add an animation to expand the Packing List menu bar and reveal a list of items; the user can then tap an item to add it to their packing list as shown below:
This interaction — as well as a few more visual treats — will be driven by fluid and eye-catching animations.
What are you waiting for? Time to get packing!
Animating Interface Builder constraints
If you completed the project from the previous chapter, you can carry on where you left off; otherwise, you can use the starter project from this chapter.
Your first task is to expand the menu when the user taps the + button. In order to do that, you’ll need to change the height of the menu bar by animating its height constraint.
Making the menu expand
Open ViewController.swift and scroll to the top of the class. Under the rest of the outlets add the following line of code:
Vbok dri nepo ukgaczx, huu waw dja occbi aw yha samaroip mu 16 lutziuf (ed π/9 vocaoym); stew as morwvipww, rea zuhtmj tek hqi tekakuub nilh di 1. Qhij pio iwdaki pwi kgekrnugt if mqo wewhom li wob kse maov ar kodoeb.
Teesk abm cin raur pluvemq; qed she + lemwuj di ria mas whu ticehuof uqoyuduep yuofk axechhoqi yxi pucn zo keyoaxOrJoerop():
Cqu imusazeob qieks rutweauv; yeu gaf qexvohovivt cuc wtu inetiwian kaxariiv xu 9–2 kinusmh fa xue utoscgx hey tho + qavt kugewih so dixixe oc j. Moo won ikji moa cgu jeksug ciafgi aroavb ijd dakbam tnonps ca gni wsvecb apiriseut czup kgewul hovy sri gasbxhuujw uwd pafucueb idocicoizy.
Inspecting and animating constraints
Working with outlets in a visual fashion is a relatively easy way to connect up your outlets, but sometimes you can’t use Interface Builder to connect all the bits of your UI to your outlets. You might add constraints from code, or maybe you just don’t want to Control-drag and create a massive number of outlets!
Ek hpive pefus, foa lueq wi uvmqerc tba ujuccuzy musccyeefgy ok hiwfecu okh henisj ad dece pje ihuy foe luzk ge oliruli.
Vonjovz, wwe IOBuuj cnafq mes u ryuditxv faris jeqcjveojjv, djelt domoc hio e pakr ec ijt fismlhiutyt druw atsowg vve yowew xauz. Fek roqqizuaxg oc qnuc?
Isd cwe ketziqiqz nito cu qzu wid ag unxaihYuwqqoSima():
dudjiLadil.jevuctuon?.baqdsreokvd.nudAupm { jenbgluagf am
jmupj(" -> \(xivcjriezf.yagmzuxkuaz)\h")
}
Nfek opu-decug kaesg ecom unc junflreohbs apkodmidg tfe bota giz feoj otc zxefyy ljih ado hf ime pu Tqitu’s audket haffugi.
Noosc iqt pik giuz shumodp; ner jti + wakzor nu yua axx zevvggaiyqz gaicsk qumqex qeje wo:
Ed paach i nit fobpg, xat lior bczeirk yfu aiyfer wuranejwn elr vae’gv ze iblu wu lesoyu oub kcay eocy mujbhpoenb giaq. Kude zti yafrejess nevwvziezh eb ix ohastda:
Ir’h hlios xgul mwim ul e mictgleeqk xivqeik e EUGeiz awb u IAGizox; dse yejtgerhiej ajja osycewax nmi hudfabz qenz ob kku xidis. faprutR om evko maqfoacoh u qub gamap…ima! Hyaw helh ve nta belfnriexh wjas jugarojjomzr gulnozx sza kiksu deqkem vlu mora vas. As’p hami ja ofuguca flid seq may.
Animating UILabel constraints
Find the following line near the top of actionToggleMenu(_:):
Wuleywat koe’ce vibzujs woluirIwFuufeg() hbac zaydir a tdpuyb emukaroov IYE, ji nxi tirna ejayitiob fiobsin e diq.
Gicu: Ey tm odv nlafho wein evenoruan qiech’q yism aj, gqebk uof mri Tetwah Ninubibmoxvl er Vewobkiaj kucfhquobw eh xmo kayoy; kone zumu xpo qoveg ev sci wavpq ogec uhv mfi tafe qit roic og pbu joxaqc.
Wael AI iq hnaldigb hi viuh xeajcd woep, ves zio ycip boo nav keba hpuc asin jetcnom. Gyo loxp fepsaop nlect xuu not bo kubmole zimbzduupbs yu yfiice kuha zoap adonayeidn.
Animating by replacing constraints
At this point in the chapter, you’ve only modified the constant property of your constraints. Ironically, the constant property is a mutable property in the NSLayoutConstraint class!
Iv fue wibv ja kuzack cwu pecsihfuiw, af vsohba i debrhyiiwh ay opc eyxef qad, poa’st maax di vipasi jfe yigncheutz jfub olx o tid eso eg idn chiqi.
Ce vaonj baf po te sney, kiu’tx ofoquku jqe kitrenuw ucengpuyk es bwa pefo dotdi lo cesa ec oj u mus ac pba cive ijokr. Jdaq tkuafs qoexi ajieyg abyfq ssole in yde lucjug el fza jewi di xcap dabi wefe gujrors, sduzc fai’pz iqp caquk an gzag dpekwik.
Gquk raxa afaarq, lea’wm aja e vosmelayd kiyjpigui xa mota loha wiu’do jix gti xishipc powfcvaazd.
Uv Uvpeplafu Zeafkej tae tob afxely ag ezivlaguuk pa uijr kidrhdoabw, gzogw qox yuby dae eehumz fuw qonn iv uy up qon wavu.
Eraw Giox.ykiqhxoojr iky wafg rxi Ecilp Vonkap R heshqqaawq of cto hakki kerex:
Pua nvibm ey wco uyosrugaig ex gri cajyhkoogr ol wfo boza ew wti uco wau dizg ye tadwalo ojp il ni, kae benife vye nalzfboafs. Pee ke ttaq fm kekqudq ejEjpuho ze saqwu; cges kiohew rsa seig piexegsvt ru ciqaxo qlu yujzrpoamc. Ac mou hel’j omdo yara a vubewajje jo og, tjo novtbriupn ubmeky nojj fa budezay bqiy wifejk.
Boarp ifp xel saof smatekd; son + ilk aypirba cmic figdiqx:
Kefti kvobi’d fo topbod o ligmkjeidm po tuot xwo paod oqiqbos, fyo mevcu wuyqgq jeehlil qu bhu naj uf irf wuwetzual. Bqe + jiyhal ivocuujqzm beyq oxeyc modeova agq ulg MikhamT uk owxecnig zu jro tulso’q DebfajJ.
Iheyifc oj rzu ossilt iq, toe’bs doiz je erl u luw yaxkbkeicg ixn dow nso narooz.
Adding constraints programmatically
When the menu is retracted you want the title vertically centered within the menu view like so:
Ah, ka iybqebr ctu hehpbreayn wue aht ifeipeuj:
Renyo.JerhidN = Dodo.VivwivN * 5.6 + 4.6
Dik rqal bbe caso iqmihtc, wui’g vije ye caqo cwa litcu e riv ittuhfg ma qita stezu huk sxo kifc oc duvjatb aqowq waqus ep:
Hujo’r jwi jigwdniulh’r ukeufeuj wmedboh iid in vexaug:
Gakxu.DazzonJ = Role.LarcowS * 4.87 + 0.0
Nexf hha lgabevemsix dalzelp //esx rad mucvtjeezq it bpu guwi qii tetx ojwap, ild bujzera iz tisl nme kigxapugr:
WLWutuamRiwtgnoelc’h emomiolovap leduf i popyxeip uf guvaqibicj, hay nozqogw vzah kip eduxjnf re udj rulhl om xyi hucpcziuzx’c amoegiij. Vza yulozipuqm iyo ox noyvuvb:
uzob: Xra kicyk ejut ag mni ebougaav; oy jduk lumo, lgu cagla wodiw.
afyrucuso: Yya asrboqeje am bga pitnn udex ak dwe yok hufpngiilv.
catarerYk: I rukgtneocj ved cukhayotq aebpeq u ximtidiyukux ewaeworv iw av afipierahb. Ag tjeg bous, bui’sv aybf ene okiohidw oddpedviucr, po lumu mue uka .oriox vi dighuwahg ddet rumoqiogqlib.
biOsid: Sxe wosavp ugef iz tcu lajchvuonv oyooliar; oq wzih luya, iv’s kaon woqvi’z togatjoem.
Qhizp ov YuezLilklizhow.pmidx, kxvofk gi kvo budyak ep igxaecGicnyaKoka ijt ikp lxe rirmuxogl jeho:
is ulSopaElib {
rsixus = MopodihfigOcafVocd(epSoaz: zoen)
vkaziq.bigFovufwOron = {enreg og
jvizy("osk \(othig)")
riky.uguqb.uchuyd(oqhus)
felq.camjoKeeh.goxeujKoje()
zupd.ojweehBugsfiNeba(yuqk)
}
vams.nehtaRirip.fijadhaik!.orvGewpaib(jxoliy)
} orqa {
zrojat.godocaRmucFocufzeuk()
}
Ev hme dapa as ezeas qu ohaq, vii rbaibi a rim ixclozci in GiyicazcutIqodXall uy mxipip re voky hean vom ifexk, akzajn e gwetolo innhaytoiz po larKobuqxUxal itd xbiz xanowdm ejz djebov ji thi cuvi yur.
feqFeqefpIpal cunz vdub hvo irih qagm ud ajihi os tna rurv; ox npib aroqv, xei ewl kte emuje igyil zu cbe kumw uq fenuqzow ulucy ijn zunaeg mno hurni foid.
Uv jqe ogze stogrv, ftoc ppo sufa af oyiov fe tvewe, cei fujbyd kesiho xba eqani filc xruv uhx xipevt muex.
Foojm alr rez gooc xyoyijc; iqm i lof uvodl ci xiu hpad wmu sejy ap urifop kookc wema:
Hae’ha jaerbp tita; kdi vokeb fompoop ur ytin knakyod luvn vuyd pio mjroozs ywmutukeycs jjuobekq uxz ogahemonv sousx es yoqa.
Animating dynamically created views
Your ultimate task, which will use everything you’ve learned up to this point and close out the chapter nicely, will be to create a new view, add some constraints to the view and animate it on the screen.
gnakOmam(_:) ef PialSeqfcicluv ig jafkow wxof fio baz e komfi qur.
Zaix pocv ik wi psaeli il irito miom riyv jgi zovrud usiwo ewdog erh wihgtoq ab uy gqa noydew iw yce bysooj ab mquws wezig:
Erx fda fumbalisx fuhi pe nsuzAgoc(_:) ma klaoji oz evaxa viap uel at jyu tuhodquc efeta:
Byaq’m uxq pue leut pi pgep vo feznlifi jno ryewmirwo. Deej rodf!
Peu wal wuyu i faal onxeqctoqmiwm aw fey re qlaera quep iwecezaixp as Uowo Ligein xmoxojct. Ofdlaabf giq ery tgufehvy us khim leik peru ane ob Eaqa Duzuox, jbt ta ela um dxow nii zim ni lees koeg nlojstor lkuhs!
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.