如何在 iOS 应用程序 (Swift) 中单击选项卡栏项目时重定向到 rootviewcontroller
How to redirect to rootviewcontroller on click of Tab bar item in iOS App (Swift)
我正在 iOS 应用 UITabBar
和 Swift 中的 UINavigationViewController
。现在面临一个问题,
如果我 select 第一个选项卡,我可以看到 'A' ViewController
,然后单击 'A' 的任何内容,我重定向到 'B' UINavigationViewController
,现在如果我点击第二个选项卡,然后再次点击第一个选项卡,它会显示 'B' NavigationViewController
。预期是,它应该显示 'A' ViewController
。如何实现?
@IBAction func itemB(sender: UIButton) {
// do something
self.tabBarController?.selectedIndex = 0
}
尝试实施 didSelectViewController
委托,然后在选择 'A ViewController' 索引时重定向到根目录 viewcontroller。
func tabBarController(tabBarController: UITabBarController, didSelectViewController viewController: UIViewController) {
let index : Int = (tabBarController.viewControllers?.indexOf(viewController))!
if index == 0
{
let navigationController = viewController as? UINavigationController
navigationController?.popToRootViewControllerAnimated(true)
}
}
在Swift3.1
将 UITabBarControllerDelegate
添加到您的 TabBar Class:
class YourClass: UITabBarController, UITabBarControllerDelegate {
之后:
override func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
let yourView = self.viewControllers![self.selectedIndex] as! UINavigationController
yourView .popToRootViewControllerAnimated(false)
}
我正在 iOS 应用 UITabBar
和 Swift 中的 UINavigationViewController
。现在面临一个问题,
如果我 select 第一个选项卡,我可以看到 'A' ViewController
,然后单击 'A' 的任何内容,我重定向到 'B' UINavigationViewController
,现在如果我点击第二个选项卡,然后再次点击第一个选项卡,它会显示 'B' NavigationViewController
。预期是,它应该显示 'A' ViewController
。如何实现?
@IBAction func itemB(sender: UIButton) {
// do something
self.tabBarController?.selectedIndex = 0
}
尝试实施 didSelectViewController
委托,然后在选择 'A ViewController' 索引时重定向到根目录 viewcontroller。
func tabBarController(tabBarController: UITabBarController, didSelectViewController viewController: UIViewController) {
let index : Int = (tabBarController.viewControllers?.indexOf(viewController))!
if index == 0
{
let navigationController = viewController as? UINavigationController
navigationController?.popToRootViewControllerAnimated(true)
}
}
在Swift3.1
将 UITabBarControllerDelegate
添加到您的 TabBar Class:
class YourClass: UITabBarController, UITabBarControllerDelegate {
之后:
override func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
let yourView = self.viewControllers![self.selectedIndex] as! UINavigationController
yourView .popToRootViewControllerAnimated(false)
}