4

我有一个 UIHostingController 托管一个名为 CatalogView 的 SwiftUI 视图。显示它时,附加了一个环境对象,所以基本上从 UIKit 显示它是这样的:

let rootCatalogView = CatalogView()

let appState = AppState.get()
let catalogView = UIHostingController(rootView: rootCatalogView.environmentObject(appState))

navigationController.pushViewController(catalogView, animated: true)

现在稍后我需要检查这个 UIHostingController 是否在 navigationController.viewControllers 列表中

type(of:) 显示以下内容,哪种有意义:

UIHostingController<ModifiedContent<CatalogView, _EnvironmentKeyWritingModifier<Optional<AppState>>>>

诸如 vc.self 是 UIHostingController.Type 或 vc.self 是 UIHostingController< CatalogView >.Type 之类的东西都返回 false (vc 是 navigationController.viewControllers 的一个元素

以下显然有效,它返回 true,但是 UIHostingController 初始化中的任何更改都会更改其类型

vc.isKind(of: UIHostingController<ModifiedContent<CatalogView, _EnvironmentKeyWritingModifier<Optional<StoreManager>>>>.self)

如何检查视图控制器是否属于 UIHostingController 类型?或者至少我怎样才能将控制器转换为 UIHostingController 以便我可以检查它的 rootview?

4

1 回答 1

1

由于泛型参数,我们无法在UIHostingController不知道完整约束的情况下强制转换 ViewController 来查找它是否为 a。

我应该指出,这不是一个理想的解决方案,它实际上只是一种解决方法。

UIHostingController是的子类,UIViewController因此我们可以执行以下操作。

在其上创建一个计算属性,UIViewController该属性返回用于创建的类的名称UIViewController。这使我们可以在ViewControllers包含在UINavigationController

extension UIViewController {
    var className: String {
        String(describing: Self.self)
    }
}

创建一些 UIViewController 子类和我们的 UIHostingController

class FirstViewController: UIViewController {}
class SecondViewController: UIViewController {}
class MyHostingController<Content>: UIHostingController<Content> where Content : View {}

let first = FirstViewController()
let second = SecondViewController()
let hosting = UIHostingController(rootView: Text("I'm in a hosting controller"))
let myHosting = MyHostingController(rootView: Text("My hosting vc"))

然后我们可以将这些添加到UINavigationController.

let nav = UINavigationController(rootViewController: first)
nav.pushViewController(second, animated: false)
nav.pushViewController(hosting, animated: false)
nav.pushViewController(myHosting, animated: false)

现在我们的 UINavigationController 中有一些 ViewController,我们现在可以遍历它们并找到一个 ViewController,它的 className 包含我们正在寻找的内容。

for vc in nav.viewControllers {
    print(vc.className)
}

这会将以下内容打印到控制台:

第一视图控制器

第二视图控制器

UIHostingController<文本>

MyHostingController<文本>

然后,您可以for-where在层次结构中找到 ViewController。

for vc in nav.viewControllers where vc.className.contains("UIHostingController") {
    // code that should run if its class is UIHostingController
    print(vc.className)
}

for vc in nav.viewControllers where vc.className.contains("MyHostingController") {
    // code that should run if its class is MyHostingController
    print(vc.className)
}

正如我上面所说,这不是一个理想的解决方案,但它可能会对您有所帮助,直到有一种更好的铸造方式而不知道通用约束。

于 2021-03-16T12:08:36.303 回答