【问题标题】:How can I update the navigation title when I select a new tab?选择新标签时如何更新导航标题?
【发布时间】:2021-06-07 20:59:11
【问题描述】:

我有一个带有三个 SwiftUIView(HomeView、FavoritesView 和 ContactsView)的 tabview 这些视图中的每一个都类似于下面的主视图。

struct HomeView: View {
var body: some View {
    VStack {
        Image(systemName: "house.fill")
        Text("This is the Home View")
    }
}

}

我的内容视图如下所示:

struct ContentView: View {
var body: some View {
    NavigationView {
        TabView {
            HomeView()
                .tabItem {
                    Label("Home", systemImage: "house")
                        .navigationBarTitle("Home")
                }
            
            FavoritesView()
                .tabItem {
                    Label("Favorites", systemImage: "star")
                        .navigationBarTitle("Favorites")
                }
            
            ContactsView()
                .tabItem {
                    Label("Contacts", systemImage: "person")
                        .navigationBarTitle("Contacts")
                }
        }
    }
}

}

但是当我运行该应用程序时,每个选项卡都会为导航标题获得相同的“主页”标题。

如何使用正确的选项卡更新导航标题(无需在每个 SwiftUI 视图中添加导航视图)我相信我们应该能够仅使用一个导航视图来实现这一点?对吗???

【问题讨论】:

  • 请发布代码,而不是代码图片,不能搜索、复制/粘贴、屏幕阅读器可读等。
  • 我发布了代码。抱歉,我不知道这一切是如何运作的,哈哈

标签: swiftui swiftui-navigationview swiftui-tabview


【解决方案1】:
//Create an enum for your options
enum Tabs: String{
    case home
    case favorites
    case contacts
}
struct TitledView: View {
    //Control title by the selected Tab
    @State var selectedTab: Tabs = .favorites
    var body: some View {
        NavigationView {
            TabView(selection: $selectedTab) {
                Text("HomeView()").tag(Tabs.home)
                    .tabItem {
                        Label("Home", systemImage: "house")
                    }
                    //Set the tag
                    .tag(Tabs.home)
                
                Text("FavoritesView()")
                    .tabItem {
                        Label("Favorites", systemImage: "star")
                            
                    }
                    //Set the tag
                    .tag(Tabs.favorites)
                
                Text("ContactsView()")
                    .tabItem {
                        Label("Contacts", systemImage: "person")
                    }
                    //Set the tag
                    .tag(Tabs.contacts)
                    
            }.navigationTitle(selectedTab.rawValue.capitalized)
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-12
    • 2016-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多