如何通过动画以编程方式更改标签栏?

时间:2018-06-24 17:23:38

标签: ios swift tabbar

我正在尝试通过动画方式以编程方式更改应用程序中的标签栏。

在我的标签栏委托类中,我目前有这个,它是从this thread获得的。

func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {

    guard let fromView = selectedViewController?.view, let toView = viewController.view else {
        return false
    }

    UIView.transition(from: fromView, to: toView, duration: 0.3, options: [.transitionCrossDissolve], completion: nil)

    return true
}

上面的动画会在用户点击时更改标签栏,但不适用于通过编程方式更改标签栏的情况,例如这种情况:

// code in another class
self.tabBarController?.selectedIndex = 2 // does not animate

我读过this thread,它提出了类似的问题,但是它是用Objective-C编写的,距今已有4年。

是否有任何方法可以对程序化选项卡栏的变化进行动画处理?

1 个答案:

答案 0 :(得分:2)

作为解决方法,您可以手动触发动画。我不知道是否建议这样做,但是它对我有用。

    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        animateTabBarChange(tabBarController: tabBarController, to: viewController)
        return true
    }

    func animateTabBarChange(tabBarController: UITabBarController, to viewController: UIViewController) {
        let fromView: UIView = tabBarController.selectedViewController!.view
        let toView: UIView = viewController.view

        // do whatever animation you like

    }

然后您这样称呼它:

let index = 2
animateTabBarChange(tabBarController: self.tabBarController!, to: self.tabBarController!.viewControllers![index])
self.tabBarController?.selectedIndex = index
相关问题