我是 SwiftUI 的新手。我有一个 ContentView,因为我添加了 NavigationView 并从该 NavigationView 重定向到另一个具有 TabView 的 View 。
//ContentView.swift
struct ContentView: View {
@State private var isValidLogin : Bool = false
var body: some View {
NavigationView{
VStack
{
NavigationLink(destination: HomePage(), isActive:$isValidLogin) {
Text("LOGIN")
.font(.headline)
.foregroundColor(.white)
.padding()
.onTapGesture {
self.isValidLogin = true
}
}
}.padding()
}
}
}
这里是 HomePage.swift 的代码
import SwiftUI
struct HomePage: View {
private enum Tab: Hashable {
case home
case map
}
@State private var selectedTabbar : Tab = .home
var body: some View {
TabView(selection: $selectedTabbar)
{
HomeView()
.tag(0)
.tabItem{
Text("Home")
Image(systemName: "house.fill")
}
MapView()
.tag(1)
.tabItem {
Text("Map")
Image(systemName: "map")
}
}.navigationBarTitle("Settings")
}
}
struct HomePage_Previews: PreviewProvider {
static var previews: some View {
HomePage()
}
}
这里是 MapView.swift 的代码
import SwiftUI
struct MapView: View {
var body: some View {
Text("You are in Map Page")
.navigationBarTitle(Text("Map"), displayMode: .inline)
}
}
struct MapView_Previews: PreviewProvider {
static var previews: some View {
MapView()
}
}
我的错误是:当我将全局标题设置为 TabView 属性时 .navigationBarTitle("Settings") 始终会反射(reflect)。但我希望这样,如果我将 NavigationTitle 设置到 subview 中,那么它将显示在该 subview 中。当我们点击 map 项时,我需要这样的导航标题应该 map 。我无法找到错误,为什么当我们将导航标题应用于子项时它不起作用。
任何帮助都应该表示赞赏。提前致谢。
最佳答案
我找到了解决方案。
在这里我更改了我的主页
:
struct HomePage: View {
@State private var selectedTabbar = 0
var body: some View {
TabView(selection: $selectedTabbar)
{
HomeView()
.tag(0)
.tabItem{
Text("Home")
Image(systemName: "house.fill")
}
MapView()
.tag(1)
.tabItem {
Text("Map")
Image(systemName: "map")
} Image(systemName: "gear")
}
}.navigationBarTitle(Text(navigationBarTitle))
.navigationBarBackButtonHidden(true)
.accentColor(.red)
}
}
我为 HomePage
添加了一个扩展。它正在设置 subview 的导航标题:
private extension HomePage {
var navigationBarTitle: String {
selectedTabbar == 0 ? "Home" : "Map"
}
}
使用此扩展,我们可以将动态导航标题设置到 TabView
中。
关于swiftui - 我无法在 SwiftUI 中将 NavigationItemTitle 覆盖到 TabView 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65544976/