Sunday, March 26, 2023
Learning Code
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#
No Result
View All Result
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#
No Result
View All Result
Learning Code
No Result
View All Result
Home Swift

iOS custom transition tutorial in Swift

learningcode_x1mckf by learningcode_x1mckf
October 8, 2022
in Swift
0
iOS custom transition tutorial in Swift
74
SHARES
1.2k
VIEWS
Share on FacebookShare on Twitter


2018/04/26

On this tutorial, you will discover ways to change the push, pop and modal animations with customized transitions & % pushed interactions.

UIKit

UIKit customized transition API – a theoretical lesson

There are various courses and delegates concerned through the course of of constructing a custom transition, let’s stroll by means of this stuff actual fast, and do some coding afterwards.

UIViewControllerTransitioningDelegate

Each view controller can have a transition delegate, in that delegate implementation you possibly can present the customized animation and interplay controllers. These objects might be answerable for the precise animation course of, and this delegate is the place the place you possibly can “inject your code” to the UIKit framework. 💉💉💉

UINavigationControllerDelegate

The navigation controller delegate additionally has two strategies which can be answerable for customized push and pop animations. It is nearly the identical because the transitioning delegate for the view controllers, however you will see this in motion in a while. 💥

UINavigationController.Operation

The navigation controller operation is simply an enum which comprises the “path” of the navigation animation. Normally push or pop.

Presenting and dismissing one thing modally shouldn’t be precisely the identical factor as pushing & popping view controllers inside a navigation stack. Extra on this later.

UIViewControllerAnimatedTransitioning

These objects are returned by the transition delegate, so mainly that is the place the place you implement the flowery customized view animations. 😉

UIViewControllerContextTransitioning

This context encapsulates all the information concerning the transitioning, you may get the taking part views, controllers and plenty of extra from this object. The transitioning context is out there so that you can use it through the animation.

UIPercentDrivenInteractiveTransition

An object that drives an interactive animation between one view controller and one other.

In a nutshell, that is the factor that provides you the magical capacity to swipe a navigation controller interactively again (and forth when you modified your thoughts) along with your fingers from the sting of the display. 📱


Customized transition animations programmatically

Let’s do some actual coding! I am going to present you easy methods to make a fundamental fade animation between view controllers inside a navigation stack. First we’ll begin with the push animation.

open class FadePushAnimator: NSObject, UIViewControllerAnimatedTransitioning 

    open func transitionDuration(utilizing transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval 
        return 0.5
    

    open override func animateTransition(utilizing transitionContext: UIViewControllerContextTransitioning) 
        guard
            let toViewController = transitionContext.viewController(forKey: .to)
        else 
            return
        
        transitionContext.containerView.addSubview(toViewController.view)
        toViewController.view.alpha = 0

        let length = self.transitionDuration(utilizing: transitionContext)
        UIView.animate(withDuration: length, animations: 
            toViewController.view.alpha = 1
        , completion:  _ in
            transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
        )
    

As you possibly can see making a customized transition animation is actually easy. You simply need to implement two delegate strategies. Certainly one of them will return the length of the animation, and the opposite will comprise the precise transition.

The transition context gives a customized containterView object that you should utilize within the animation, additionally you possibly can seize the taking part views and controllers from this object as I discussed it earlier than. Now let’s reverse this animation. 👈

open class FadePopAnimator: CustomAnimator 

    open func transitionDuration(utilizing transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval 
        return 0.5
    

    open override func animateTransition(utilizing transitionContext: UIViewControllerContextTransitioning) 
        guard
            let fromViewController = transitionContext.viewController(forKey: .from),
            let toViewController = transitionContext.viewController(forKey: .to)
        else 
            return
        

        transitionContext.containerView.insertSubview(toViewController.view, belowSubview: fromViewController.view)

        let length = self.transitionDuration(utilizing: transitionContext)
        UIView.animate(withDuration: length, animations: 
            fromViewController.view.alpha = 0
        , completion:  _ in
            transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
        )
    

Lastly you simply need to implement the navigation controller’s delegate technique with a purpose to change the built-in UIKit system animations. 🛠

extension MainViewController: UINavigationControllerDelegate 

    func navigationController(_ navigationController: UINavigationController,
                              animationControllerFor operation: UINavigationController.Operation,
                              from fromVC: UIViewController,
                              to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? 
        swap operation 
        case .push:
            return FadePushAnimator()
        case .pop:
            return FadePopAnimator()
        default:
            return nil
        
    

Word that you do not have to make two separate courses (pop & push), you too can move the operation and implement the animations in a single animated tarnsitioning class.


P.c pushed interactive transitions

So, now you understand how to implement a customized transition, however it is time to make it interactive! The method is fairly easy, you will solely want a gesture recognizer and a correct delegate technique to make issues work. ⌨️

class DetailViewController: UIViewController 

    var interactionController: UIPercentDrivenInteractiveTransition?

    override func viewDidLoad() 
        tremendous.viewDidLoad()

        self.view.backgroundColor = .lightGray

        let edge = UIScreenEdgePanGestureRecognizer(goal: self,
                                                    motion: #selector(self.handleEdgePan(_:)))
        edge.edges = .left
        self.view.addGestureRecognizer(edge)
    

    override func viewDidAppear(_ animated: Bool) 
        tremendous.viewDidAppear(animated)

        self.navigationController?.delegate = self
    

    @objc func handleEdgePan(_ gesture: UIScreenEdgePanGestureRecognizer) 
        let translate = gesture.translation(in: gesture.view)
        let % = translate.x / gesture.view!.bounds.dimension.width

        swap gesture.state  velocity.x > 0 
                self.interactionController?.end()
            
            else 
                self.interactionController?.cancel()
            
            self.interactionController = nil
        default:
            break
        
    


extension DetailViewController: UINavigationControllerDelegate 

    

    func navigationController(_ navigationController: UINavigationController,
                              interactionControllerFor animationController: UIViewControllerAnimatedTransitioning)
        -> UIViewControllerInteractiveTransitioning? 

        return self.interactionController
    

Contained in the controller that might be popped you possibly can take possession of the navigation controller’s delegate and implement the interactive transition controller utilizing a left display edge pan gesture recognizer. This entire code often goes into a brand new subclass of UIPercentDrivenInteractiveTransition however for the sake of simplicity this time we’ll skip that, and go along with this very easy answer. Within the final example code you will discover the “subclassed model” of the interactive transition. 😅


Navigation vs modal presentation

Okay, let’s cowl yet another factor actual fast: customizing modal presentation animations for view controllers. There’s a minor distinction between customizing the navigation stack animations and modal presentation types. If you wish to customise a view controller transition you’d often do one thing like this. 👍

class DetailViewController: UIViewController 

     

    override func put together(for segue: UIStoryboardSegue, sender: Any?) 
        tremendous.put together(for: segue, sender: sender)

        guard let controller = segue.vacation spot as? ModalViewController else 
            return
        

        controller.transitioningDelegate = self
        controller.modalPresentationStyle = .customized
        controller.modalPresentationCapturesStatusBarAppearance = true
    

Right here comes the transitioning delegate, utilizing the identical objects that we have already got.

extension DetailViewController: UIViewControllerTransitioningDelegate 

    func animationController(forPresented offered: UIViewController,
                             presenting: UIViewController,
                             supply: UIViewController) -> UIViewControllerAnimatedTransitioning? 
        return FadePushAnimator()
    

    func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? 
        return FadePopAnimator()
    

When you run the code and current the modal view controller, that’ll work simply wonderful. The issue happens once you attempt to dismiss the offered view controller. The entire app will flip to a black screen of dying (BSOD). 🖥

(pop != dismiss) && (push != current)

You need to modify the pop animation with a purpose to help modal dismissal animations. In brief: the issue is with putting views and reminiscence administration.

open class FadePopAnimator: NSObject, UIViewControllerAnimatedTransitioning 

    public enum TransitionType 
        case navigation
        case modal
    

    let sort: TransitionType
    let length: TimeInterval

    public init(sort: TransitionType, length: TimeInterval = 0.25) 
        self.sort = sort
        self.length = length

        tremendous.init()
    

    open func transitionDuration(utilizing transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval 
        return self.length
    

    open override func animateTransition(utilizing transitionContext: UIViewControllerContextTransitioning) 
        guard
            let fromViewController = transitionContext.viewController(forKey: .from)
        else 
            return
        

        if self.sort == .navigation, let toViewController = transitionContext.viewController(forKey: .to) 
            transitionContext.containerView.insertSubview(toViewController.view, belowSubview: fromViewController.view)
        

        let length = self.transitionDuration(utilizing: transitionContext)
        UIView.animate(withDuration: length, animations: 
            fromViewController.view.alpha = 0
        , completion:  _ in
            transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
        )
    

The most straightforward answer is to introduce a brand new property so you can also make a call to pop or dismiss the view controller based mostly on that flag. Now you possibly can safely use the identical animators for modally offered view controllers as effectively. 😬

The pattern code is inside The.Swift.Dev. tutorials repository, you will discover examples for changing the default push & pop navigation animations with customized ones.

Word that the navigation bar will all the time use a fade animation, sadly that may not be custom-made. Additionally I’ve made a customized modal presentation, and all the pieces is utilizing the interactive transitions too. Clearly there may be much more, however under are some hyperlinks which you could comply with when you hit an impediment throughout your journey.

Additionally when you do not wish to manually implement customized animation results you should utilize Hero the elegant transition library.



Source link

You might also like

Introducing – AI Utils for macOS

Encoding and decoding data using the Hummingbird framework

Hummingbird routing and requests – The.Swift.Dev.

Share30Tweet19
learningcode_x1mckf

learningcode_x1mckf

Recommended For You

Introducing – AI Utils for macOS

by learningcode_x1mckf
March 24, 2023
0
Introducing – AI Utils for macOS

⚠️ REQUIRES a FREE OpenAI API key. You will get one utilizing this hyperlink. ⚠️ Improve your productiveness with our AI powered utility application. - accessible...

Read more

Encoding and decoding data using the Hummingbird framework

by learningcode_x1mckf
March 22, 2023
0
Encoding and decoding data using the Hummingbird framework

HTTP is all about sending and receiving information over the community. Initially it was solely utilized to switch HTML paperwork, however these days we use HTTP to switch...

Read more

Hummingbird routing and requests – The.Swift.Dev.

by learningcode_x1mckf
March 17, 2023
0
Hummingbird routing and requests – The.Swift.Dev.

Routing on the server facet means the server goes to ship a response primarily based on the URL path that the consumer referred to as when firing up...

Read more

Building a Scrollable Custom Tab Bar in SwiftUI

by learningcode_x1mckf
March 10, 2023
0
Building a Scrollable Custom Tab Bar in SwiftUI

Whether or not you’re making a social media app or a productiveness device, the tab bar interface can improve the consumer expertise by making it extra intuitive and...

Read more

Beginner’s guide to server-side Swift using the Hummingbird framework

by learningcode_x1mckf
March 8, 2023
0
Beginner’s guide to server-side Swift using the Hummingbird framework

Swift on the Server in 2023 Three years in the past I began to focus on Vapor, the preferred web-framework written in Swift, which served me very...

Read more
Next Post
JavaScript developer destroys own projects in supply chain “lesson” – Naked Security

JavaScript developer destroys own projects in supply chain “lesson” – Naked Security

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Related News

Google expands open source bounties, will soon support Javascript fuzzing too – ZDNet

OpenJDK Java 20 Released With Latest Vector API, Scoped Values – Phoronix

March 21, 2023
Google expands open source bounties, will soon support Javascript fuzzing too – ZDNet

Javascript Redirects & SEO: When & How To Use Them – Search Engine Journal

March 5, 2023
Senior Java Developer – IT-Online

Senior Java Developer – IT-Online

September 10, 2022

Browse by Category

  • C#
  • C++
  • Java
  • JavaScript
  • Python
  • Swift

RECENT POSTS

  • YS Jagan launches Ragi Java in Jagananna Gorumudda, says focused on intellectual development of students – The Hans India
  • Disadvantages of Java – TheServerSide.com
  • Advantages of Java – TheServerSide.com

CATEGORIES

  • C#
  • C++
  • Java
  • JavaScript
  • Python
  • Swift

© 2022 Copyright Learning Code

No Result
View All Result
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#

© 2022 Copyright Learning Code

Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?