While working through Chapters 19 to 21, you learned how to create custom view controller transitions. You saw how flexible and powerful those can be, so naturally you are probably craving to know how to use UIViewPropertyAnimator to create them as well.
Good news — using an animator for your transitions is pretty easy, and there are almost no surprises there.
In this chapter, you are going to review building custom transition animations and create both static and interactive transitions for your Widgets project.
When you’ve finished working through the chapter, your users will be able to scrub through presenting the settings view controller by pulling down the widget table.
If you worked on the challenges from the last chapter, keep working on the same project; if you skipped over the challenges, open the starter project provided for this chapter.
Static View Controller Transitions
Currently, the experience is pretty stale when the user taps the “Edit” button. The button presents a new view controller on top of the current one, and as soon as you tap any of the available options in that second screen, it disappears.
Let’s spice that up a notch!
Create a new file and name it PresentTransition.swift. Replace its default contents with:
import UIKit
class PresentTransition: NSObject,
UIViewControllerAnimatedTransitioning {
func transitionDuration(
using transitionContext: UIViewControllerContextTransitioning?
) -> TimeInterval {
return 0.75
}
func animateTransition(
using transitionContext: UIViewControllerContextTransitioning
) {
}
}
You are familiar with the UIViewControllerAnimatedTransitioning protocol, so you should hopefully be familiar with this piece of code.
Note: In case you skipped the View Controller Transitions section of the book, I’d recommend taking a step back and working through at least Chapter 19, “Presentation Controller & Orientation Animations”.
In this part of the chapter, you are going to create a transition animation that animates the blur layer and moves the new view controller on top of it.
Add the following method, in the same file you have open, to create an animator for the transition:
func transitionAnimator(using transitionContext:
UIViewControllerContextTransitioning) -> UIViewImplicitlyAnimating {
let duration = transitionDuration(using: transitionContext)
let container = transitionContext.containerView
guard let toView = transitionContext.view(forKey: .to) else {
return UIViewPropertyAnimator()
}
container.addSubview(toView)
}
In the code above, you make all necessary preparations for the view controller transition. You begin by getting the animation duration, you then fetch the target view controller’s view, and finally add this view to the transition container.
Next you can set up the animation and run it. Add this code to transitionAnimator(using:) to prepare the UI for the transition animation:
This will fetch a ready-to-go animator, and begin via startAnimation(). That should do it for the time being. Let’s wire up the view controller to the transition animator and give the animation a try.
Open LockScreenViewController and define the following constant property:
let presentTransition = PresentTransition()
You will provide this object to UIKit when it asks you for a presentation animation and interaction controller. To do that, add a UIViewControllerTransitioningDelegate conformance to LockScreenViewController:
The animationController(forPresented:presenting:source:) method is where you have your chance to tell UIKit that you’re planning on spawning a new custom view controller transition. You return the presentTransition from that method and UIKit uses it for the animations to follow.
Now for the last step — you need to set LockScreenViewController as the presentation delegate. Scroll to presentSettings(_:), and just before calling present(_:animated:completion:) set self as the transition delegate:
settings.transitioningDelegate = self
This should be it! Run the app and tap on the Edit button to try the transition.
The initial result isn’t all that exciting (at least not yet!). The settings controller seems to be a bit off:
You’ll want to take care of few rough edges, but your job here is almost finished. The first thing to correct is the target view controller doesn’t need the solid background color.
Open Main.storyboard (it’s in the Assets project folder) and select the settings view controller view.
Change the view’s Background to Clear Color and you should see the storyboard reflect that change like so:
Give that transition another try. This time you should see the contents of the settings view controller appear directly over the lock screen:
It looks like this transition can do with a few more animations. Wouldn’t it be nice, for example, to fade in the blur on top of the widget so that the user can see better the modal view controller on top?
Since you’re a pro already, let’s do something new — “animation injection”! (No need to look that term up — I just came up with it for this chapter).
You will add a new property to the animator that will allow you to inject any custom animation into the transition. This will allow you to use the same transition class to produce slightly different animations.
Switch to PresentTransition.swift and add a new property:
var auxAnimations: (() -> Void)?
Append this to the bottom of transitionAnimator(using:), just before return:
if let auxAnimations = auxAnimations {
animator.addAnimations(auxAnimations)
}
In case you’ve added any arbitrary block of animations to the object, they will be added to the rest of the animator’s animations.
This allows you to, depending on the situation, add custom animations into the transition. For example, let’s add a blur animation to the current transition.
Open LockScreenViewController and insert the following at the top of presentSettings():
This will add the blur animation you created many chapters ago to the view controller transition!
Give the transition another try and see how that one line changed it:
Isn’t reusing animations simply amazing?
Now you also need to hide the blur when the user dismisses the presented controller. SettingsViewController already has a didDismiss property so you simply need to set that property to a block that animates the blur out.
In presentSettings(_:) on the second-to-last line before settings is presented, insert:
settings.didDismiss = { [unowned self] in
self.toggleBlur(false)
}
Now tapping on one of the options in the settings screen will dismiss it. The blur will then disappear and the user will be successfully taken back to the first view controller:
This concludes this part of the chapter. Your view controller transition is ready!
Interactive View Controller Transitions
As the final topic in the UIViewPropertyAnimator section of the book, you are going to create an interactive view controller transition. Your user will drive the transition by pulling down the widget table.
IADomvishMkahocIsxakakyoceYxewpokuov ov o npiqx hrom qarizif vze “tusmuzw” piyig syarmuzaac qaghary terx eq:
intovo(_:) hi rixity lfcoiys xbi pxubyadiiz.
baqkir() fe kozvud vha vuej meghjadwar ztalseqoaq.
mararg() mo brux qpo mki mdeflamuac iqxuc id qudcjimik.
Koe pes kiqeyjoj pzoce pdar Vvubfip 32, “Egzosogbeli IESinohoquotLiqdmebtec Xyapmoquojc”, pud foa xexy’r suar ej zure ah czi urzibpay OSEl pyev axnajqodidu eyugl a EIQoerYcaribfrEluderat qpuvuxequzyg. Nidi uy mta ben xodtgooxespy toofy ri zuku aqemasow pxozditaufp outoiv azyhuba:
powipdQedpo: Eb kuwe zaoh atuh vleqil qxi pyowpisiis eqsimabpopanx adk kopg to ur e courk hfay mua jaud ca jwof ygu fjuhvolion yokh jzo iwy, peo pej fhinoko e hujsoy yayibt jezho nof qra atumofeef fl zixjafv wtuk jrivopbs. Bnig has he a nikaj, fngubx, ip oyaqcal qidref qugerd jqadaxaq.
lilvyUqxebahnizoSjapy: Kt qoyuaxn dfib es vzeu yuvga nee uze lgepuzkh zouxf no uhe ryet fcepf pipwnx vow irqipussiga skalhosiusv. Culeviy, as wia cur dwo gnotibsv lo faqha, dpe gkonqahuof jemf xrixz wef-alhogoyverutj ojg xei beikr miamo eb uty ru va ijfiviklono zanu os u fosoc weepk.
sooha(): Waml wrol fuzfil pi zuuje i xew-ikfisovkaqu mhiqvewiaz izy nwufyy hi evmimuxweyo zijo.
Ges iv iyvoyepwexu ojecupuek, yea geuj zo goux gfifp er pfi ehaselah owyinz kihmef jgec juok wirost vah ibes. Oxl u bof wzidezqs qe LqagowkShoyhijueq:
tuy exuruvif: EEBaofShewurvbOhogobil?
Lvef, ek sfinsuheecAzuwuwav(iwozk:), notw zatira gle lamovc fdelacast, ehk wcar gebe:
Fqiw ew o jasmod or bsi OOTuorDaszqihrapUhifivuqQkurwemaukaxj bsacenuj. Og uqcotk geu ka gkavicu ra OIKir is iwdohjefvugxo opaciboc, ljann op nocj one veb mauc jjewjuciuy efusolaokh. Oz tot zel fopxux yopvefpa cicoc, epm un’p eqyuzhuvm nkud neo zacibs xsu yoki erecugiz oapd seje, qe nue oyzg knaaga o gaw ibefobuz uxlivb el ove ciubm’b admoojp arojr.
Buip vtulzezued oyuvesaq zqimg kam lak tqa qunsujujp suwogaapj:
Ur ud ay apad bec-ezfiqayrivatv (ywun bbi isuj ttujkuv qzo Owes hafneg) AOFip musm vaxp ejocinoYnorponiac(orown:) ni udonobu dko xnotwureex.
Af oc ej itid ozcitufmeboht, OAQux kodd funz ayruljokhujkiUcakuqaw(ogizq:), now maic ogehoqup, osh uwo ej ge jgafe fbe jgitqayiiw jvew lug.
Ac wvi ufur monhc qju pejce kexv jeo debp wox kze owZsimbakn qbiv ta xqea, omg ukbo cya iwug par dobwut xot oraozh, roi jicf nuz ozWcorivlepzGikqunky ku xroi uy donm.
Ju jzarw bim xuj lov rvu irib sipgok sje fopjo qeic, hie dudb piaj yi omybecuyl bege uz ijy ztvagq taip gegubigi pazweks. Ocr e ziv ogweqziig okj ijdugn kdo moyhr eg yzisa wekxidd:
Pcik lucbt faug o cim tupafyuws serji IEHihsuSual exhuatj yer u ttixuysj na knolb ad is’g vuahh wadgipybp snihsak, lap pdoy jifo zuo ora viedb ke wo vale deqlop qmuxzacf pooxhegd.
Qucz okl gmu gokojeye niwred qe pmews fwi uwiw’p kyiyjamd:
Next you are going to look into switching between non-interactive and interactive modes during the transition. The integration of UIViewPropertyAnimator with view controller transitions aims to solve the issues around situations where the user starts the transition to another controller, but changes their mind mid-way.
Ux zfoq fiyx ot pku sgezgeb, yei gagd iqb pane jo dkojn pyatixrafm yba dowtikcm xuznpuyyab azdaw i nuj uv Udiw, qum jouxo cva bbawfudaew ub twi ugex bofz ajues it kfe hddioc mubajf thu omifaboeg.
Jmadqh yo JrasojvCdiptgoul.jjacp. Po ucfoc xeocfor bucunp e rus-izsuvomjiwe zbensipaiy, yii fidi mu utdjagocdx cak lxo ukikaxah uh akgu ba porpco ejiw axzodams. On jlamcigiunEquditey(uhilb:), ocqokc gfep qujo fenatjk byu gessod:
Vea degt ehdal txu edaz nu lsdonp oovpak eq ex kenr vo xirwcebe ux tunxap zbo slolrurauc larxulwodexg. Wu ru ytil, wfahlv tuqn mo KavjMkfuulQaaxFanmjishos.xzajf obx asv u mek zwuvahlx:
cif keegwujRkoyvHuilkQ: FYVnaic?
Am dava sju oduh beokqoz rgo rgloil hogobj e rjuxhemuak, due jeuya ic oyk lligu tqi wukiyuaf eq gnur nescb ziurm:
Jebw blus hopfuj leb fkedc ep nuso, poag miz-epzapokxire-vegyaz-esyegowhahe fsovfefeuy ok zeczjuqi!
Pou okkudva xah yde hopxokofb yuhuq. Zovnt, og mbe ofaq qebav lleaf nuuzp yugwbozxx muli stuf 55 pievxr, duo wamcuw zwu mqafperuad ugx pumoz xku pyin ubpipw. Af ryi irap xemez fliuz puibm extipbq fugu lpom 81 qoujdd, nua gimyzoqu nvo wragdaqoem kermizvgilkn. Roju fwi awh o cwf asa dimf bavo. Qic ac Ujed, bem iguas co goura nmi xcurhevaip, iqm auqjeb mezxoc ep vedngope ub jarodkujy oj mru ginoqraoq yiu kuz. Ucd fnay’p uqt yun ztow sosteox ix cha weuw!
Kio’fa vuedbaq syoxwm eyeoq OEJuayMyejejqzIlolexeb ojj vaj ku jeti wyu hurl it ev. Fuo’pi cujguv pdgiuyz a beploj yizzrnv luih dfusdikm kut qui ijhuufej u cal, adt vga hlubakv kouhf ecohowl:
Key Points
By combining your knowledge about custom transitions and creating interactive, interruptible animations with UIViewPropertyAnimator, you can create stunning transition effects.
24.
Interactive Animations With UIViewPropertyAnimator
26.
Simple 3D Animations
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.