解决TabView不保存View状态
2年前 • 1048次点击 • 来自 移动端
标签: SwiftUI
原文链接:TabView resets navigation stack when switching tabs
UIKitTabView.swift
SwiftUI下一般如下使用TabView:
TabView {
NavigationView {
VStack {
NavigationLink(destination: Text("Detail")) {
Text("Go to detail")
}
}
}
.tabItem { Text("First") }
.tag(0)
Text("Second View")
.tabItem { Text("Second") }
.tag(1)
}
但是,SwiftUI当前的TabView会重置Navigation的Stack,如果你需要来回切换Tab的同时保存View的状态,那么暂时可通过UIViewControllerRepresentable调用UITabBarController来实现:
UIKitTabView.swift
使用示例:
struct ExampleView: View {
@State var text: String = ""
var body: some View {
UIKitTabView([
UIKitTabView.Tab(
view: NavView(),
barItem: UITabBarItem(title: "First", image: nil, selectedImage: nil)
),
UIKitTabView.Tab(
view: Text("Second View"),
barItem: UITabBarItem(title: "Second", image: nil, selectedImage: nil)
)
])
}
}
struct NavView: View {
var body: some View {
NavigationView {
VStack {
NavigationLink(destination: Text("This page stays when you switch back and forth between tabs (as expected on iOS)")) {
Text("Go to detail")
}
}
}
}
}