从TabBarController呈现特定的ViewController

时间:2017-02-15 02:59:25

标签: swift uinavigationcontroller uitabbarcontroller uistoryboard unusernotificationcenter

每当触发本地通知并执行自定义操作时,我想从ViewController打开特定的TabBarController。我使用了以下代码行

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 ...

2 个答案:

答案 0 :(得分:1)

使用此:

tabBarController.selectedIndex = 1

1 可以是viewcontrollers

提供的tabBarController中的任何一个

答案 1 :(得分:1)

我遇到了类似的问题,更改selectedIndex对我来说不起作用。根据项目的要求,您可以实例化 ViewController并将其添加为Subview并移至Subview。完成后,请务必删除Subview

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