在我的 SwiftUI/UIKit 项目中,我们使用 UIKit 的导航控制器进行导航。目前,我有一个从 SwiftUI View 获取 UIViewController 的函数:
func popTo<T: View>(viewType: T.Type, animated: Bool) {
if let viewController = rootNavigationController.viewControllers.first(where: {
$0.self.description.contains(String(describing: viewType))
}) {
self.rootNavigationController.popToViewController(viewController, animated: animated)
}
}
我想让它更加健壮,而不依赖于字符串。我想直接按类型过滤。这是一个例子:
if let firstHostingController = rootNavigationController.viewControllers.first(where: { $0 is UIHostingController<MyView> }){
self.popToView(viewController: firstHostingController, animated: true)
}
鉴于我们正在 UIKit 导航控制器中工作,如何在不使用字符串进行类型比较的情况下修改我的 popTo 函数?
您的第二个代码片段即将完成。只需将
MyView
替换为类型参数 T
。
extension UINavigationController {
func popTo<T: View>(viewType: T.Type, animated: Bool) {
if let firstHostingController = viewControllers.first(where: { $0 is UIHostingController<T> }){
self.popToViewController(firstHostingController, animated: true)
}
}
}