繁体   English   中英

Swift:如何通过导航栏按钮访问选项卡栏项

[英]Swift: How to access a tab bar item by pressing a nav bar button

我目前有一个CustomTabBarController类和一个CustomNavBarController类。

标签栏有五个标签,可以正常工作。 导航栏类在导航栏的右侧添加了三个按钮(主页/消息/配置文件)。 单击主页按钮时,将触发以下功能。

CustomNavBarController.swift(只有tappedHome功能)

func tappedHome(sender: UIButton) {
     // Go to home page (tab bar index 0)
}

这是我的AppDelegate和CustomTabBar文件。

AppDelegate.swift

    window?.rootViewController = CustomTabBarController()
    let tabBar: UITabBarController = self.window?.rootViewController as! UITabBarController
    tabBar.selectedIndex = 0

CustomTabBarController.swift

class CustomTabBarController: UITabBarController, UITabBarControllerDelegate {

override func viewDidLoad() {

    super.viewDidLoad()

    self.delegate = self

    self.viewControllers = [createDummyNavControllerWithTitle("News", imageName: "icon_news", viewController: MainController()),
                            createDummyNavControllerWithTitle("Games", imageName: "icon_games", viewController: GamesController()),
                            createDummyNavControllerWithTitle("Students", imageName: "icon_students", viewController: StudentsController()),
                            createDummyNavControllerWithTitle("Ranking", imageName: "icon_rank", viewController: StatsController()),
                            createDummyNavControllerWithTitle("Info", imageName: "icon_info", viewController: InfoController())]
}

func tabBarController(tabbarController: UITabBarController, didSelectViewController viewController: UIViewController) {

     self.title = viewController.title
}

// Shortcut function for the tab bar items
private func createDummyNavControllerWithTitle(title: String, imageName: String, viewController: UIViewController) -> UINavigationController {

    viewController.title = title

    let navController = UINavigationController(rootViewController: viewController)
    navController.tabBarItem.title = title
    navController.tabBarItem.image = UIImage(named: imageName)?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)

    return navController
}
}

单击主页按钮时,如何告诉CustomNavBarController.swift中的函数加载选项卡栏的第一个索引?

PS:之所以我想有两种方法可以返回首页,是因为选项卡栏在每种情况下都不可见。

在您的tappedHome(_:)方法中执行以下代码应该可以解决问题:

let appDelegate  = UIApplication.sharedApplication().delegate as! AppDelegate
let tabBarController = appDelegate.window!.rootViewController as! UITabBarController
tabBarController.selectedIndex = 0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM