如何切换选项卡栏控制器中的选项卡,以便委派方法通知用户切换选项卡?

时间:2017-02-09 19:01:23

标签: ios swift

我尝试了selectedIndexselectedViewController,但他们没有调用添加动画的委托。

Storyboard

标签栏代理:

class TabBarViewController: UITabBarController, UITabBarControllerDelegate {

override func viewDidLoad() {
    super.viewDidLoad()
    self.delegate = self
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}
func animateToTab(toIndex: Int) {
    let tabViewControllers = viewControllers!
    let fromView = selectedViewController!.view
    let toView = tabViewControllers[toIndex].view
    let fromIndex = tabViewControllers.index(of: selectedViewController!)

    guard fromIndex != toIndex else {return}

    fromView?.superview!.addSubview(toView!)

    let screenWidth = UIScreen.main.bounds.size.width;
    let scrollRight = toIndex > fromIndex!;
    let offset = (scrollRight ? screenWidth : -screenWidth)
    toView?.center = CGPoint(x: (fromView?.center.x)! + offset, y: (toView?.center.y)!)

    view.isUserInteractionEnabled = false

    UIView.animate(withDuration: 0.5, delay: 0.0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: UIViewAnimationOptions.curveEaseOut, animations: {

        fromView?.center = CGPoint(x: (fromView?.center.x)! - offset, y: (fromView?.center.y)!);
        toView?.center   = CGPoint(x: (toView?.center.x)! - offset, y: (toView?.center.y)!);

    }, completion: { finished in

        fromView?.removeFromSuperview()
        self.selectedIndex = toIndex
        self.view.isUserInteractionEnabled = true
    })
}

func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
    let tabViewControllers = tabBarController.viewControllers!
    guard let toIndex = tabViewControllers.index(of: viewController) else {
        return false
    }
    animateToTab(toIndex: toIndex)
    return true
}
}

2 个答案:

答案 0 :(得分:0)

有些时候我需要和你一样的东西。 我做的是Subclass UITabBarController,将故事板上的主tabbarcontroller设置为此子类,并在appdelegate上将其设置为rootViewController,假设用户已登录。

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
{
     //This will inform you about the selected tab.
    NSUInteger indexOfTab = [[tabBar items] indexOfObject:item];

}

在斯威夫特:

 func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {

       var indexOfTab = tabBar.items.indexOfOBject(item)
    }

答案 1 :(得分:0)

我使用SwipeableTabBarController pod解决了这个问题。

pod 'SwipeableTabBarController'

在项目目录

中的终端pod install

打开创建的.xcworkspace文件

然后import SwipeableTabBarController

删除animateToTab功能和shouldSelect viewController 将班级从class TabBarViewController: UITabBarController, UITabBarControllerDelegate更改为class TabBarViewController: SwipeableTabBarControllerviewDidLoad()

override func viewDidLoad() {
    super.viewDidLoad()
    setSwipeAnimation(type: SwipeAnimationType.push)
}