SwiftUI:再次轻按选定的选项卡时,弹出到根视图
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SwiftUI:再次轻按选定的选项卡时,弹出到根视图相关的知识,希望对你有一定的参考价值。
起点是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()
完整模块代码:
import SwiftUI
struct TestPopToRootInTab: View
@State private var selection = 0
@State private var resetNavigationID = UUID()
var body: some View
let selectable = Binding( // << proxy binding to catch tab tap
get: self.selection ,
set: self.selection = $0
// set new ID to recreate NavigationView, so put it
// in root state, same as is on change tab and back
self.resetNavigationID = UUID()
)
return TabView(selection: selectable)
self.tab1()
.tabItem
Image(systemName: "1.circle")
.tag(0)
self.tab2()
.tabItem
Image(systemName: "2.circle")
.tag(1)
private func tab1() -> some View
NavigationView
NavigationLink(destination: TabChildView())
Text("Tab1 - Initial")
.id(self.resetNavigationID) // << making id modifiable
private func tab2() -> some View
Text("Tab2")
struct TabChildView: View
var number = 1
var body: some View
NavigationLink("Child \(number)",
destination: TabChildView(number: number + 1))
struct TestPopToRootInTab_Previews: PreviewProvider
static var previews: some View
TestPopToRootInTab()
以上是关于SwiftUI:再次轻按选定的选项卡时,弹出到根视图的主要内容,如果未能解决你的问题,请参考以下文章