Swift ios send user to a specific ViewController in tab based application

假如想象 提交于 2019-12-24 05:59:21

问题


I want to send a user to a specific ViewController in my app once a notification is clicked.

I now that I can do something like this:

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let destinationViewController = storyboard.instantiateViewControllerWithIdentifier("Home") as? HomeViewController
presentedVC?.presentViewController(destinationViewController!, animated: true, completion: nil)

But my app has a tab bar and looks like this

Tab bar

tab1: navigationController -> VC1

tab2: navigationController -> VC2 -> HomeVC

tab: navigationController -> VC3

Each tab has a navigationController as a infront of it.

So how can I send the user to HomeVC? I must first select tab 2 then the navigation controller then push the user tvice:

tab2: navigationController -> VC2 -> HomeVC

And the other problem, if there any way to tell if the user is already in HomeVC? I dont want to send the user to the same VC if his already there.


回答1:


You must have access to your UITabbarController in you UIApplicationDelegate or wherever you're handling the notification tap.

let tabBar:UITabBarController = self.window?.rootViewController as! UITabBarController //or whatever your way of getting reference is

So first you'll get the reference to UINavigationController in your second tab like this:

let navInTab:UINavigationController = tabBar.viewControllers?[1] as! UINavigationController

Now push your home view at second tab's navigation controller:

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let destinationViewController = storyboard.instantiateViewControllerWithIdentifier("Home") as? HomeViewController
navInTab.pushViewController(destinationViewController!, animated: true)

And finally switch your tab to second to show the just pushed home controller

tabBar.selectedIndex = 1

Keep in mind, this answer assumes that your application has already set the tab bar as the root view controller of application window prior handling the notification tap.




回答2:


Try something like this:

if let tabBarController = window?.rootViewController as? UITabBarController {
  tabBarController.selectedIndex = 1 // in your case the second tab
}

The idea is to switch to get the tab bar instance and switch it to your desired tab (where you have your view controller).

The above code works in AppDelegate / you can easily call it anywhere by getting the tabBarController instance.




回答3:


You can check which tab is selected by user with the method var selectedIndex: Int. You can check which view controller is present like this self.navigationController?.presentingViewController?.presentedViewController. This will solve your problem.



来源:https://stackoverflow.com/questions/40508632/swift-ios-send-user-to-a-specific-viewcontroller-in-tab-based-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!