如何解决选择新标签时如何更新导航标题?
我有一个包含三个 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)
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。