ios - Swift - 从 AppDelegate 添加 subview 到 View Controller

标签 ios swift uikit

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

@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)
        }
    }
}

最佳答案

问题在于,警报消息实际上是一个 UIViewController 以模态方式呈现在您的原始 UIViewController 上。如果您想到达顶部的shown View Controller (不是presented),您可以将此方法添加到您的AppDelegate。如果您使用导航堆栈,它将返回 Root View Controller 或顶 View Controller 。

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

希望对你有帮助

关于ios - Swift - 从 AppDelegate 添加 subview 到 View Controller,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52339714/

相关文章:

UIViewControllerRepresentable : Navigation Title and Bar Button Items Ignored in NavigationView

ios - UIControl.sendAction 的选择器的目的是什么?

android - 如何清理我的 react-native 项目以备份它?

ios - 使用 Alamofire 上传图片不成功

swift - 清空 Collection View Swift

ios - 在 SwiftUI 中使用 UIViewControllerRepresentable 呈现 UIDocumentInteractionController

ios - 多个简单UIView的内存管理

ios - 在某种情况下移动到下一个屏幕?

ios - Swift:如何知道哪个 Storyboard 处于事件状态

animation - 处理 iOS 10 中的 AutoLayout 约束动画差异?