IOS Development--transition animations

Source: Internet
Author: User

"Using a Guevara movie, or any other app may know that a click of a button to achieve a transition animation is now very popular, the effect is generally as follows:"

This article is the swift version, the OC version will be left behind the demo download

In iOS, in the same navigation controller you can customize transition animations to achieve transitions between two viewcontroller. In fact, after iOS7, by implementing

UIViewControllerAnimatedTransitioning或者UIViewControllerContextTransitioning协议,


You can simply customize the transition animations, such as a navigationcontroller push and pop. One more thing you need to know is that if I have a rectangle with a circle and want to cut out the same area as the circle size on this rectangle, then use the Calayer Mask property, and the following diagram representation might be intuitive:

Now maybe you have a little understanding of the Mask property, the implementation of the following code you will see the specific implementation process. To do so much first, let's start with the next step.

Start to implement simple push effects

New project, here is swift, select Storyboard, and then add a navigation, as follows


Then the effect is as follows

The right side of the shows Navigation bar removed, because the demo does not need a navigation bar, while ensuring that is instal View controller was hooked (do not know the child shoes can be removed to see the effect), here the default is checked on. Then create a new Viewcontroller and set it to inherit from Viewcontroller, as follows

Then on two VC respectively in the same position to add two exactly the same button, position constraints in the upper right corner distance from the right and the top of the 20,20, in order to differentiate, the two VC set different background color, as follows

Then right-click on the first button and drag it to the second VC (that is, the yellow background) Tap Show

At this time, there will be a line between two VC, and then click the middle of the line, set identifier to Pushsegue, here set an identifier, for the following jump to prepare, the effect is as follows:

Connect the two buttons to the same property of Viewcontroller, named Popbtn, and then implement a click Method for the second VC button (because we want pop back) named Popclick, as follows

import UIKitclass ViewController: UIViewController {    @IBOutlet weak var popBtn: UIButton!    override func viewDidLoad() {        super.viewDidLoad()        // Do any additional setup after loading the view, typically from a nib.    }    @IBAction func popClick(sender: AnyObject) {        self.navigationController?.popViewControllerAnimated(true)    }    override func didReceiveMemoryWarning() {        super.didReceiveMemoryWarning()        // Dispose of any resources that can be recreated.    }}

Finally, add a imageview in the middle of each of the two VC, and the last one is as follows

If you are right here, run your project and the effect will be the same

Yes, it's a simple push effect, and now the preparation is done, the animation that wants to zoom in, and goes on.

Starting to achieve amplification effect

With the above steps, we are ready to work, and one thing we need to know is that to customize the push or pop effect of the navigation, it is necessary to implement the Uinavigationcontrollerdelegate protocol.

func navigationController(navigationController: UINavigationController,interactionControllerForAnimationController animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {    return nil}

This protocol method, we first create a new class named Hwnavigationdelegate inherited from NSObject, and then introduce uinavigationcontrollerdelegate to implement the above protocol method, Leave the return value temporarily nil (as you can see from the above code, the return value is an optional value, so you can use nil first, and then implement it later). And the code inside your hwnavigationdelegate is roughly the following.

////  HWNavigationDelegate.swift//  HWAnimationTransition_Swift////  Created by HenryCheng on 16/3/16.//  Copyright © 2016年 www.igancao.com. All rights reserved.//import UIKitclass HWNavigationDelegate: NSObject, UINavigationControllerDelegate {    func navigationController(navigationController: UINavigationController, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {        return nil;    }}

Now continue to open storyboard, then search for object in the lower right corner and drag it to the left navigation Controller source,

and select object to change its class to the hwnavigationdelegate you just created on the right.


Finally on the left, click Uinavigationcontroller and set its delegate to just the object

Now the return value of the protocol method for navigating inside the hwnavigationdelegate is nil, we need to create a class that animates the effect and make it return, Here we create a new class named Hwtransitionanimator that also inherits from NSObject, and enables it to implement the Uiviewcontrolleranimatedtransitioning protocol, and the Protocol method therein, in order to facilitate reading, All the code is posted here,

hwtransitionanimator.swift//hwanimationtransition_swift////Created by Henrycheng on 16/3/16.//copyright©2016 Year www.igancao.com. All rights Reserved.//import Uikitclass Hwtransitionanimator:nsobject, uiviewcontrolleranimatedtransitioning {weak VA    R transitioncontext:uiviewcontrollercontexttransitioning?     Func transitionduration (transitioncontext:uiviewcontrollercontexttransitioning?), Nstimeinterval {return 0.5  } func animatetransition (transitioncontext:uiviewcontrollercontexttransitioning) {Self.transitioncontext = Transitioncontext Let Containerview = Transitioncontext.containerview () Let Fromvc = Transitioncontext.view Controllerforkey (Uitransitioncontextfromviewcontrollerkey) as! Viewcontroller Let ToVC = Transitioncontext.viewcontrollerforkey (uitransitioncontexttoviewcontrollerkey) as! Viewcontroller Let button = Fromvc.popbtn containerview?. Addsubview (tovc.view) Let circlemaskpathinitial = UIBezierpath (ovalInRect:button.frame) Let Extremepoint = Cgpoint (x:button.center.x-0, Y:button.center.y-cgrect GetHeight (toVC.view.bounds)) Let radius = sqrt ((extremepoint.x * extremepoint.x) + (EXTREMEPOINT.Y * extremepoint.y ) Let circlemaskpathfinal = Uibezierpath (Ovalinrect:cgrectinset (Button.frame,-radius,-radius)) Let MaskL Ayer = Cashapelayer () Masklayer.path = Circlemaskpathfinal.cgpath ToVC.view.layer.mask = masklayer le T masklayeranimation = cabasicanimation (keypath: "path") Masklayeranimation.fromvalue = Circlemaskpathinitial.cgpat H Masklayeranimation.tovalue = Circlemaskpathfinal.cgpath masklayeranimation.duration = Self.transitionDurat  Ion (transitioncontext) masklayeranimation.delegate = self masklayer.addanimation (masklayeranimation, ForKey: "Path")} override Func Animationdidstop (anim:caanimation, finished flag:bool) {Self.transitioncontext?. Completetransition (!self.transitioncontext!. Transitionwascancelled ()) Self.transitioncontext? Viewcontrollerforkey (Uitransitioncontextfromviewcontrollerkey)?. View.layer.mask = nil}}


About all the code above, where

func animateTransition(transitionContext: UIViewControllerContextTransitioning),func animateTransition(transitionContext: UIViewControllerContextTransitioning)


Is the way to set the time and animation process, are

UIViewControllerAnimatedTransitioning的协议方法,func animationDidStop是实现动画结束后的操作,


After the animation is over, it is necessary to cancel the animation and release the Fromviewcontroller. Inside the

let circleMaskPathInitial = UIBezierPath(ovalInRect: button.frame)let extremePoint = CGPoint(x: button.center.x - 0, y: button.center.y - CGRectGetHeight(toVC.view.bounds))let radius = sqrt((extremePoint.x * extremePoint.x) + (extremePoint.y * extremePoint.y))let circleMaskPathFinal = UIBezierPath(ovalInRect: CGRectInset(button.frame, -radius, -radius))let maskLayer = CAShapeLayer()maskLayer.path = circleMaskPathFinal.CGPathtoVC.view.layer.mask = maskLayer


This code, the second section of the code below the beginning of the Masklayer this is said, the first piece of code is actually a calculation process, to find out the radius of the final round effect, the principle (rough painting a bit, the painting is not good forgive ^_^)

Finally, we can modify the return value of the protocol method in hwnavigationdelegate just to Hwtransitionanimator object.

func navigationController(navigationController: UINavigationController, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {    return HWTransitionAnimator()}


If the above steps, you do the right thing, the operation of the project results are as follows

Adding a gesture-guided animation
添加手势实现动画效果,我们在刚才的<br>HWNavigationDelegate类里实现UINavigationControllerDelegate的另外一个斜一方法func navigationController(navigationController: UINavigationController,interactionControllerForAnimationController animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {    return self.interactionController}


Here's

self.interactionController


Is our navigation controller, such as

Then rewrite the awakefromnib () method for the final code implementation of the entire hwnavigationdelegate, as follows
Hwnavigationdelegate.swift//Hwanimationtransition_swift////Created by Henrycheng on 16/3/16. COPYRIGHT©2016 year www.igancao.com. All rights reserved. //

Import Uikitclass Hwnavigationdelegate:nsobject, uinavigationcontrollerdelegate {@IBOutlet weak var Navigationcontrol    ler:uinavigationcontroller!    var interactioncontroller:uipercentdriveninteractivetransition?    Func Navigationcontroller (Navigationcontroller:uinavigationcontroller, Interactioncontrollerforanimationcontroller animationcontroller:uiviewcontrolleranimatedtransitioning) Uiviewcontrollerinteractivetransitioning?  {return Self.interactioncontroller} func Navigationcontroller (Navigationcontroller:uinavigationcontroller, Animationcontrollerforoperation operation:uinavigationcontrolleroperation, Fromviewcontroller FromVC: Uiviewcontroller, Toviewcontroller tovc:uiviewcontroller), uiviewcontrolleranimatedtransitioning?    {return hwtransitionanimator ()//return nil; } override func awakefromnib () {super.awakefromnib () Let pangesture = Uipangesturerecognizer (Target:sel F, Action:selector ("panned:")) Self.navigationController.view.addGestureRecognizer (pangesture)} func panned (gesturerecognizer:uipanges Turerecognizer) {switch Gesturerecognizer.state {case. Began:self.interactionController = Uipercentdriveninteractivetransition () if Self.navigationcontrol Ler?. Viewcontrollers.count > 1 {self.navigationcontroller?. Popviewcontrolleranimated (True)} else {Self.navigationcontroller?. topviewcontroller!. Performseguewithidentifier ("Pushsegue", Sender:nil)} case. Changed:let translation = Gesturerecognizer.translationinview (self.navigationcontroller!. view) Let completionprogress = Translation.x/cgrectgetwidth (self.navigationcontroller!. View.bounds) Self.interactioncontroller? Updateinteractivetransition (completionprogress) case. Ended:if (Gesturerecognizer.velocityinview (self.navigationcontroller!.              view). x > 0) {  Self.interactioncontroller?. Finishinteractivetransition ()} else {Self.interactioncontroller?. Cancelinteractivetransition ()} Self.interactioncontroller = Nil Default:self.int Eractioncontroller?. Cancelinteractivetransition () Self.interactioncontroller = nil}}}


It is important to note that there are several states of Gesturerecognizer

1. Begin: Gestures are recognized and initialized

UIPercentDrivenInteractiveTransition


instance objects and setting properties, such as if the first VC implements push, or the other is pop

2, Changed: Start gesture to the end of a process of gesture, the above code is based on the offset change

self.interactionController


The location

3, Ended: The operation after the end of the gesture, set the animation end or cancel the animation, and finally

Self.interactioncontroller


Set to nil

4, Default: Other state to run your project, drag the screen when the effect is as follows

At last

IOS Development--transition animations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.