【发布时间】:2020-06-26 16:16:06
【问题描述】:
起点是 TabView 中的 NavigationView。当再次点击选定的选项卡时,我正在努力寻找一个 SwiftUI 解决方案以弹出到导航堆栈中的根视图。在 SwiftUI 之前的时代,这很简单:
func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
let navController = viewController as! UINavigationController
navController.popViewController(animated: true)
}
你知道如何在 SwiftUI 中实现同样的事情吗?
目前,我使用以下依赖于 UIKit 的解决方法:
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
let navigationController = UINavigationController(rootViewController: UIHostingController(rootView:
MyCustomView() // -> this is a normal SwiftUI file
.environment(\.managedObjectContext, context)
))
navigationController.tabBarItem = UITabBarItem(title: "My View 1", image: nil, selectedImage: nil)
// add more controllers that are part of tab bar controller
let tabBarController = UITabBarController()
tabBarController.viewControllers = [navigationController /*, additional controllers */]
window.rootViewController = tabBarController // UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
}
【问题讨论】: