Как создать анимацию перекрестного растворения при переключении между вкладками - PullRequest
0 голосов
/ 29 мая 2019

Как можно записать простую анимацию перекрестного растворения в классе контроллера вкладок, который выполняется при переключении между вкладками.

Вот пример приложения, показывающего этот вид анимации.

Я довольно новичок в пользовательских анимациях перехода. Я понимаю, что это должно происходить в рамках didSelect

override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {

}

enter image description here

UPDATE

Кажется, с моей стороны есть некоторая путаница:

Я создал новый файл Swift с именем TabBarClass.swift

Внутри я добавил следующий код:

    class MyFadeTransition: NSObject, UIViewControllerAnimatedTransitioning {
        func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
            if let fromVC = transitionContext.viewController(forKey: .from), let toVC = transitionContext.viewController(forKey: .to) {
                toVC.view.frame = fromVC.view.frame
                toVC.view.alpha = 0
                fromVC.view.alpha = 1
                transitionContext.containerView.addSubview(fromVC.view)
                transitionContext.containerView.addSubview(toVC.view)

                UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: {
                    toVC.view.alpha = 1
                }) { (finished) in
                    transitionContext.completeTransition(finished)
                }
            }
        }

        func animationEnded(_ transitionCompleted: Bool) {
            // no-op
        }

        func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
            return 0.3
        }
    }


**And in the AppDelegate I added:**

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        func tabBarController(_ tabBarController: UITabBarController, animationControllerForTransitionFrom fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
            let fade = MyFadeTransition()
            return fade
        }

What is the issue?

ОБНОВЛЕНИЕ 2

Вот как написан мой AppDelegate:

import UIKit

@UIApplicationMain


class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var tabBarController: UITabBarController!

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {


        let tab = window!.rootViewController as! UITabBarController
        tab.delegate = self


        return true
    }



    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }


}
extension AppDelegate: UITabBarControllerDelegate {
    func tabBarController(_ tabBarController: UITabBarController, animationControllerForTransitionFrom fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        let fade = MyFadeTransition()

        return fade
    }
}

1 Ответ

2 голосов
/ 29 мая 2019

Используйте метод UITabBarControllerDelegate:

func tabBarController(_ tabBarController: UITabBarController, animationControllerForTransitionFrom fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning?

Основная часть работы находится в классе, который соответствует UIViewControllerAnimatedTransitioning.

Вот реализация, которая пересекает два контроллера.

MyFadeTransition.swift:

import UIKit

class MyFadeTransition: NSObject, UIViewControllerAnimatedTransitioning {
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        if let fromVC = transitionContext.viewController(forKey: .from), let toVC = transitionContext.viewController(forKey: .to) {
            toVC.view.frame = fromVC.view.frame
            toVC.view.alpha = 0
            fromVC.view.alpha = 1
            transitionContext.containerView.addSubview(fromVC.view)
            transitionContext.containerView.addSubview(toVC.view)

            UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: {
                toVC.view.alpha = 1
            }) { (finished) in
                transitionContext.completeTransition(finished)
            }
        }
    }

    func animationEnded(_ transitionCompleted: Bool) {
        // no-op
    }

    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return 0.3
    }
}

Что-то в вашем коде должно быть контроллером панели вкладок delegate. Установите это, а затем реализуйте метод делегата в этом классе.

func tabBarController(_ tabBarController: UITabBarController, animationControllerForTransitionFrom fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
    let fade = MyFadeTransition()
    return fade
}

Обратите внимание, что этот же класс MyFadeTransition можно использовать с UINavigationController. UINavigationControllerDelegate имеет один и тот же базовый метод, поэтому вы можете повторно использовать класс перехода как для контроллеров панели вкладок, так и для контроллеров навигации.

Предполагая, что ваш контроллер панели вкладок является корневым контроллером вашего приложения, вы можете добавить следующий код в didFinishLaunchingWithOptions вашего AppDelegate:

let tab = window!.rootViewController as! UITabBarController
tab.delegate = self

Затем добавьте:

extension AppDelegate: UITabBarControllerDelegate {
    func tabBarController(_ tabBarController: UITabBarController, animationControllerForTransitionFrom fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        let fade = MyFadeTransition()

        return fade
    }
}

в AppDelegate.swift.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...