How to animate Tab bar tab switch with a CrossDissolve slide transition?

后端 未结 5 776
既然无缘
既然无缘 2020-12-04 11:20

I\'m trying to create a transition effect on a UITabBarController somewhat similar to the Facebook app. I managed to get a \"scrolling effect\" working on tab s

5条回答
  •  北海茫月
    2020-12-04 12:18

    To expand on @gmogames answer: https://stackoverflow.com/a/45362914/1993937

    I couldn't get this to animate when selecting the tab bar index via code, as calling:

    tabBarController.setSeletedIndex(0)
    

    Doesn't seem to go through the same call heirarchy, and it skips the method:

    tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController)
    

    entirely, resulting in no animation.

    In my code I wanted to have an animation transition for a user tapping a tab bar item in addition to me setting the tab bar item in-code manually under certain circumstances.

    Here is my addition to the solution above which adds a different method to set the selected index via code that will animate the transition:

    import Foundation
    import UIKit
    
    @objc class CustomTabBarController: UITabBarController {
        override func viewDidLoad() {
            super.viewDidLoad()
            delegate = self
        }
    
        @objc func set(selectedIndex index : Int) {
            _ = self.tabBarController(self, shouldSelect: self.viewControllers![index])
        }
    }
    
    @objc extension CustomTabBarController: UITabBarControllerDelegate  {
        @objc func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
    
            guard let fromView = selectedViewController?.view, let toView = viewController.view else {
                return false // Make sure you want this as false
            }
    
            if fromView != toView {
    
                UIView.transition(from: fromView, to: toView, duration: 0.3, options: [.transitionCrossDissolve], completion: { (true) in
    
                })
    
                self.selectedViewController = viewController
            }
    
            return true
        }
    }
    

    Now just call

    tabBarController.setSelectedWithIndex(1)   
    

    for an in-code animated transition!

    I still think it is unfortunate that to get this done we have to override a method that isn't a setter and manipulate data within it. It doesn't make the tab bar controller as extensible as it should be if this is the method that we need to override to get this done.

提交回复
热议问题