【问题标题】:SwiftUI how to refresh one single tabview without switching tabbarSwiftUI如何在不切换标签栏的情况下刷新一个标签视图
【发布时间】:2021-04-16 05:06:14
【问题描述】:

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

//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")
            }
        }
    }
}


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

【问题讨论】:

    标签: swiftui


    【解决方案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
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多