从TabBarController提供一个特定的ViewController

问题描述:

我想从TabBarController开始一个特定的ViewController,只要触发一个本地通知并执行它们的自定义操作。我用的代码以下行:从TabBarController提供一个特定的ViewController

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping() -> Void) { 

    switch response.actionIdentifier { 
    case "first": 
     DispatchQueue.main.async(execute: { 
      self.first() 
     }) 
    case "second": 
     DispatchQueue.main.async(execute: { 
      self.second() 
     }) 
    default: 
     break 
    } 


    completionHandler() 
} 

所以这是一个first()功能

func first() { 


    let storyboard = UIStoryboard.init(name: "Main", bundle: nil) 
    let tabBarController = storyboard.instantiateViewController(withIdentifier: "Root") as! UITabBarController 
    let navigationController = storyboard.instantiateViewController(withIdentifier: "First") as! UINavigationController 

    tabBarController.present(navigationController, animated: true) { 

    } 

    self.window = UIWindow.init(frame: UIScreen.main.bounds) 
    self.window?.tintColor = UIColor(red: 0.0, green: 0.5, blue: 0.0, alpha: 1.0) 
    self.window?.rootViewController = tabBarController 
    self.window?.makeKeyAndVisible() 

} 

功能second()

func second() { 


    let storyboard = UIStoryboard.init(name: "Main", bundle: nil) 
    let tabBarController = storyboard.instantiateViewController(withIdentifier: "Root") as! UITabBarController 
    let navigationController = storyboard.instantiateViewController(withIdentifier: "Second") as! UINavigationController 

    tabBarController.present(navigationController, animated: true) { 

    } 

    self.window = UIWindow.init(frame: UIScreen.main.bounds) 
    self.window?.tintColor = UIColor(red: 0.0, green: 0.5, blue: 0.0, alpha: 1.0) 
    self.window?.rootViewController = tabBarController 
    self.window?.makeKeyAndVisible() 

} 

而且它的效果很好,但我无法打开第二ViewController而第一个提出和第二通知被激发:在控制台:警告试图提出的ViewController ...

使用此:

tabBarController.selectedIndex = 1 

凡能是由您的tabBarController

+0

这似乎没用。这只是回报1 – Mannopson

+1

它不必返回任何东西。如果您将selectedIndex设置为任意数字,则选项卡栏会将其选项卡更改为所选的索引。如果您设置selectedIndex = 0,您将切换到第一个选项卡。 selectedIndex = 1,第二个选项卡。等 –

+0

感谢您的帮助。我对UITabBarController类没有任何经验。 – Mannopson

提出的viewcontrollers中的任何一个我碰到过类似的问题,并且更改selectedIndex不适合我。根据您的项目的要求,您可以实例化您的ViewController并将其添加为Subview并移至该Subview。当你完成后,一定要删除那Subview

let replyView = self.storyboard?.instantiateViewControllerWithIdentifier("replyView") 
    self.addChildViewController(replyView!) 
    self.view.addSubview(replyView!.view) 
    replyView!.didMoveToParentViewController(self) 
+0

它是如何完成的?我应该在哪里调用这些代码? – Mannopson

+1

在你希望改变'ViewController'的行动中。如果它的一个按钮动作,然后在按钮动作内调用上面的代码。 –

+0

非常感谢! – Mannopson