0

我想從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 ...

回答

1

使用此:

tabBarController.selectedIndex = 1 

凡能是由您的tabBarController

+0

這似乎沒用。這只是回報1 – Mannopson

+1

它不必返回任何東西。如果您將selectedIndex設置爲任意數字,則選項卡欄會將其選項卡更改爲所選的索引。如果您設置selectedIndex = 0,您將切換到第一個選項卡。 selectedIndex = 1,第二個選項卡。等 –

+0

感謝您的幫助。我對UITabBarController類沒有任何經驗。 – Mannopson

1

提出的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

相關問題