问题描述
我有一个包含三个 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 视图中添加导航视图)我相信我们应该能够仅使用一个导航视图来实现这一点?对吧???
解决方法
//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)
}
}
}