来自另一个视图控制器的Swift Present View控制器

时间:2017-05-17 00:27:01

标签: ios swift uiviewcontroller presentviewcontroller

我目前在主视图控制器(View Controller A)中有以下功能。

func myAction() {       
    let mainStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)
    let viewControllerC : UIViewController = mainStoryboard.instantiateViewController(withIdentifier: "ViewControllerC") as UIViewController

    self.present(viewControllerC, animated: false, completion: nil)
}

当前显示View Controller A并且调用了myAction时,它正常工作并显示viewControllerC

但是这个函数myAction基本上可以在任何时候调用。有时即使View Controller A不是屏幕上的当前视图控制器。有时显示View Controller B时,仍会调用此函数。它被称为罚款。但在这种情况下它不会加载viewControllerC

我还尝试了以下思路,可以从任何活动视图控制器中显示。但那也没有用。

self.view.window?.rootViewController?.present(viewControllerC, animated: false, completion: nil)

无论当前显示哪个视图控制器,如何在调用viewControllerC时显示myAction

2 个答案:

答案 0 :(得分:0)

您需要获取当前在应用程序中可见的顶级viewController以获取顶级viewController 使用此代码

extension UIApplication {
    class func topView(controller: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
        if let navController = controller as? UINavigationController {
            return topViewController(controller: navController.visibleViewController)
        }
        if let tabController = controller as? UITabBarController {
            if let selected = tabController.selectedViewController {
                return topViewController(controller: selected)
            }
        }
        if let presented = controller?.presentedViewController {
            return topViewController(controller: presented)
        }
        return controller
    }
}

答案 1 :(得分:0)

您已经介绍了一个View Controller,并且想从介绍的View Controller中介绍第二个View Controller,为此,您必须调用此名称:

UIApplication.shared.keyWindow?.rootViewController?.presentedViewController?.present(newViewController, animated: true, completion: nil)