如何检测模态视图在 SwiftUI 中全局可见

时间:2021-07-30 21:27:36

标签: ios swiftui uikit

在 SwiftUI 中,有几种方法可以呈现像 .popover 这样的模态视图。

我的背景是我想在其他地方而不是在当前视图页面下呈现一个 UIKit 模式视图

private func presentGlobally(animated: Bool, completion: (() -> Void)?) {
        var rootViewController = UIApplication.shared.rootViewController
        while true {
          if let presented = rootViewController?.presentedViewController {
            rootViewController = presented
          } else if let navigationController = rootViewController as? UINavigationController {
            rootViewController = navigationController.visibleViewController
          } else if let tabBarController = rootViewController as? UITabBarController {
            rootViewController = tabBarController.selectedViewController
          } else {
            break
          }
        }
        UIApplication.shared.rootViewController?.present(self, animated: animated, completion: completion)
    }

上述方法不起作用,因为 SwiftUI 给出了错误

``[演示]尝试本上<< EM> TtGC7SwiftUI19UIHostingControllerGVS_15ModifiedContentGS1_GS1_GS1_GS1_V16BuyersCircle_iOS11ContentViewGVS_30_EnvironmentKeyWritingModifierGSqCS2_11UserService ___ GS4_GSqCS2_11GlobalModal ___ GS4_GSqCS2_9CartModel ___ GS4_GSqCS2_19ReachabilityMonitor ___ GS4_GSqCS2_19PartialSheetManager ___:0x158715600>(距离

所以我在想

  • 如果我能得到当前的 SwiftUI 模态视图控制器,那么我就可以基于它来呈现 UIKit 模态。我不知道如何让它发挥作用。

1 个答案:

答案 0 :(得分:1)

在您的算法中,您正在计算 rootViewController,然后将 self 呈现给 UIApplication.shared.rootViewController,而不是找到的 rootViewController

替换

UIApplication.shared.rootViewController?.present(self, animated: animated, completion: completion)

rootViewController?.present(self, animated: animated, completion: completion)