ios - 如何在选项卡栏 Controller 中切换选项卡,以便委托(delegate)方法得知用户切换选项卡?

标签 ios swift

我尝试过 selectedIndexselectedViewController 但它们没有调用添加动画的委托(delegate)。

Storyboard

标签栏委托(delegate):

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
}
}

最佳答案

我曾经需要和你一样的东西。 我所做的是子类 UITabBarController,将 Storyboard 上的主 tabbarcontroller 设置为这个子类,并将其设置为 appdelegate 上的 rootViewController,假设用户已登录。

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

}

在 Swift 中:

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

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

关于ios - 如何在选项卡栏 Controller 中切换选项卡,以便委托(delegate)方法得知用户切换选项卡?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42144823/

相关文章:

ios - 未使用的场景从 Storyboard 中临时隐藏

swift - 如何访问从URl下载的保存文件路径

ios - 为什么 recvfrom 方法的返回值是 4294967295 应该是 0 或 -1?

ios - 将整数值从一个 ViewController 传递到另一个 ViewController 并将其显示在 UITextField 中

ios - swift 中的选项卡栏项目标签问题

ios - SocketScan 在 Swift 中获取电池电量

ios - 如果已设置 UIImageView 图像,有一种方法可以快速通知吗?

ios - AdMob 原生高级广告单元 ID

ios - 使用 Twitter/FB 共享表时是否需要包含可达性?

ios - Swift 中的基于文本的游戏