SwiftUI 如何在不切换标签栏的情况下刷新单个标签视图

时间:2021-01-11 08:49:38

标签: swiftui

我需要在网络请求完成后对某些视图进行刷新,但我的标签栏在刷新页面后自动切换到第一个 tabview,这是我的代码:

//tab view
struct PricesView: View {
    @ObservedObject var netWorkManager = NetworkManager.shareInstance
    var body: some View {
        if netWorkManager.dataList.isEmpty {
            LoadingView().onAppear(perform: netWorkManager.fetchPricesData)
        } else {
            Text("Prices").foregroundColor(.red)
        }
    }
}

...

//main view
struct ContentView: View {
    var body: some View {
        TabView {
            HomeView().tabItem {
                Image(systemName: "house.fill")
                Text("home")
            }
            AlertsView().tabItem {
                Image(systemName: "flag.fill")
                Text("alerts")
            }
            LinksView().tabItem {
                Image(systemName: "link.icloud")
                Text("link")
            }
            PricesView().tabItem {
                Image(systemName: "bitcoinsign.circle")
                Text("prices")
            }
        }
    }
}


我怎样才能避免这种情况?

1 个答案:

答案 0 :(得分:1)

使用选择和标记。

struct ContentView: View {
    
    @State var selection = 0 // <- Here declare selection
    
    var body: some View {
        TabView(selection: $selection) { // <- Use selection here
            HomeView().tabItem {
                Image(systemName: "house.fill")
                Text("home")
            }.tag(0) // <- Add tag
            
            AlertsView().tabItem {
                Image(systemName: "flag.fill")
                Text("alerts")
            }.tag(1) // <- Add tag
            
            LinksView().tabItem {
                Image(systemName: "link.icloud")
                Text("link")
            }.tag(2) // <- Add tag
            
            PricesView().tabItem {
                Image(systemName: "bitcoinsign.circle")
                Text("prices")
            }.tag(3) // <- Add tag
        }
    }
}