如何从UITabBarItem

时间:2016-02-26 02:27:19

标签: ios swift

当用户点击某个项目时,我想让ViewController与该标签相关联。

TabBar委托不再提供ViewController委托。相反,它提供didSelectItem委托。

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

如何从UITabBarItem获取ViewController?

2 个答案:

答案 0 :(得分:4)

如果您使用的是UITabBarController,而不只是UITabBar使用UITabBarControllerDelegate而不是UITabBarDelegateUITabBarControllerDelegate提供了方法:

func tabBarController(_ tabBarController: UITabBarController, 
    didSelectViewController viewController: UIViewController)

答案 1 :(得分:0)

这是适用于我的 swift 4 扩展版本:

import UIKit

extension UIApplication {

var visibleViewController: UIViewController? {

    guard let rootViewController = keyWindow?.rootViewController else {
        return nil
    }

    return getVisibleViewController(rootViewController)
}

private func getVisibleViewController(_ rootViewController: UIViewController) -> UIViewController? {

    if let presentedViewController = rootViewController.presentedViewController {
        return getVisibleViewController(presentedViewController)
    }

    if let navigationController = rootViewController as? UINavigationController {
        return navigationController.visibleViewController
    }

    if let tabBarController = rootViewController as? UITabBarController {
        // Uncomment the line bellow the TabBarController
        //return tabBarController.selectedViewController

        // uncomment the line bellow to get the visible ViewController of the TabBarController
        return getVisibleViewController(tabBarController.selectedViewController!)
    }

    return rootViewController
  }
}

可以这样简单地称呼它:

let visibleVC = UIApplication.shared.visibleViewController

我也希望这对您有用;)