首页 > 解决方案 > Swift – 从 AppDelegate 向 View Controller 添加子视图

问题描述

我正在尝试从AppDelegate当前显示添加子视图UIViewController,我注意到如果在添加子视图UIViewController时显示警报消息AppDelegate,则子视图将添加到UIAlertController而不是UIViewController. UIViewController显示子视图而不是当前UIViewController可能显示的任何其他子视图的最佳方式是什么?这是我当前的代码。

@objc func showStudentLeftTheTestAlert(notification: NSNotification) {
    if let userInfo = notification.userInfo {
        if let visibleVc = self.window?.visibleViewController {
            // do some other stuff here 
            visibleVc.view.addSubview(StudentLeftTestAlertViewController.sharedInstance.view)
        }
    }
}

标签: iosswiftuikit

解决方案


问题在于,警报消息实际上是以UIViewController模态方式呈现在您的原始UIViewController. 如果你想到达顶shown视图控制器(不是presented),你可以添加这个方法给你AppDelegate。如果您使用导航堆栈,它将返回您的根视图控制器或顶部视图控制器。

func getTopViewController() -> UIViewController? {
    let rootViewController = self.window?.rootViewController

    if let navigationController = rootViewController as? UINavigationController {
        // get the top view controller from stack if needed
        return navigationController.topViewController
    } else {
        return rootViewController
    }
}

希望对你有帮助


推荐阅读