swift - 从 TabBarController 呈现一个特定的 ViewController

标签 swift uinavigationcontroller uitabbarcontroller uistoryboard unusernotificationcenter

每当触发本地通知 并执行自定义操作时,我想从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,而第一个出现并且第二个 notification 被触发:在控制台中:警告尝试呈现 ViewController...

最佳答案

使用这个:

tabBarController.selectedIndex = 1

或者这个:

tabBarController.selectedViewController = tabBarController.viewControllers![1]

1 可以是您的 tabBarController 呈现的任何 viewcontrollers

关于swift - 从 TabBarController 呈现一个特定的 ViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42239917/

相关文章:

ios - Swift:许多内置函数返回 Optional 类型。如何在没有丑陋的嵌套 ifs 的情况下将它们变成常规变量?

swift - 创建一个带有子模块的 Swift 框架

ios - 在 UITabBarController 中声明委托(delegate)时在两个 ViewController 之间传递数据时出错

ios - 从 UITabBar 预加载 View

ios - 用户登录一次后,我在设置初始化 View Controller 时遇到问题

swift - 如何从 Swift 的 Button 中删除图像?

ios - 如何在允许设置 Root View Controller 的同时调整 UINavigationBar 的高度?

iOS 7——navigationController 正在设置我的 UIScrollView 的 contentInset 和 ContentOffset

ios - 如何使用新的导航 Controller 堆栈启动流程?

ios - 隐藏 Tabbar Controller Tabbar iOS 问题