我在 TabView 中使用导航视图,问题是如果我在选项卡 A 上使用 NavigationView 打开其他视图,当从选项卡 A 更改为 B 时,过了一会儿我回到选项卡 AI 不会重新加载选项卡 A从头开始,但它显示使用 NavitagionLink 打开的最后一个视图。问题是在每个视图中我都从数据库中获取数据,因此如果显示一个空视图。
我的 ContentView 如下所示:
import SwiftUI
struct ContentView: View {
@ObservedObject var appState = AppState()
@State var currentTab : Tab
var body: some View {
TabView(selection: $appState.currentTab) {
NavigationView {
HomeView(appState: appState)
}
.tabItem {
if appState.currentTab == .home {
Image(systemName: "house.fill")
} else {
Image(systemName: "house")
}
Text(LocalizedStringKey("HomeTabMenu"))
}.tag(Tab.home)
NavigationView {
SearchView()
}
.tabItem {
if appState.currentTab == .search {
Image(systemName: "magnifyingglass.circle.fill")
} else {
Image(systemName: "magnifyingglass")
}
Text(LocalizedStringKey("SearchTabMenu"))
}.tag(Tab.search)
NavigationView {
AddItemView(appState: appState)
}
.tabItem {
if appState.currentTab == .add {
Image(systemName: "plus.circle.fill")
} else {
Image(systemName: "plus.circle")
}
Text(LocalizedStringKey("SellTabMenu"))
}.tag(Tab.add)
NavigationView {
ShoppingCartFavoritesView()
}
.tabItem {
if appState.currentTab == .favorites {
Image(systemName: "cart.fill")
} else {
Image(systemName: "cart")
}
Text(LocalizedStringKey("CartTabMenu"))
}.tag(Tab.favorites)
NavigationView {
ProfileView(appState: appState)
}
.tabItem {
if appState.currentTab == .profile {
Image(systemName: "person.fill")
} else {
Image(systemName: "person")
}
Text(LocalizedStringKey("ProfileTabMenu"))
}.tag(Tab.profile)
}//End TabView
.accentColor(Color("ColorMainDark"))
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView(currentTab: Tab.home)
}
}
class AppState: ObservableObject {
@Published var currentTab : Tab = .home
}
enum Tab {
case home, search, add, favorites, profile
}
如果我打开 SearchView()
struct SearchView: View {
var body: some View {
NavigationLink(destination: View_2(id: "ABC")){
Text("ABC")
}
}
}
struct View_2: View {
@ObservedObject var performSearchProducts = PerformSearchInProducts()
var id : String
var body: some View {
ScollView{
ForEach(performSearchProducts.products) { product in
Text(product.name)
}
}.onAppear(perform: {
self.performSearchProducts.searchSubCategory(id: id)
})
}
}
如果在 SearchView 中,我在 View_2() 上并且我打开另一个选项卡,当我返回选项卡 SearchView 时,它不会显示 SearchView(),但它仍然在 View_2() 上,并带有导航栏中的后退按钮。
我怎样才能显示 SearchView() 而不是保持 NavigationLink 的状态?