我有一个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列表中
类型( 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,以便检查它的根视图?
发布于 2021-03-16 12:08:36
由于使用泛型参数,我们无法在不知道完整约束的情况下转换ViewController以查找它是否为UIHostingController。
--我应该注意到,这不是一个理想的修复方法,它实际上只是一项工作.
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)既然我们在ViewControllers中有了一些UINavigationController,我们现在就可以迭代它们,并找到一个包含我们正在寻找的内容的className的ViewController。
for vc in nav.viewControllers {
print(vc.className)
}这将将以下内容打印到控制台:
FirstViewController
SecondViewController
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)
}正如我前面所说的,这不是一个理想的解决方案,但它可能会帮助您,直到有一个更好的方法进行转换,而不知道泛型约束。
https://stackoverflow.com/questions/66605743
复制相似问题