解决TabView不保存View状态

1个月前 67次点击 来自 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")
                }
            }
        }
    }
}
Card image cap
开发者雷

尘世间一个小小的开发者,每天增加一些无聊的知识

本站文章全部采用 CC BY 4.0 协议,欢迎转载

技术文档 >> 系列应用 >>
热推应用
Let'sLearnSwift
学习Swift的入门教程
PyPie
Python is as good as Pie
标签