1

我是 SwiftUI 的新手。我有一个 ContentView,因为我添加了 NavigationView 并从该 NavigationView 重定向到另一个具有 TabView 的视图。

//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")总是反映。但是我想要这样,如果我将 NavigationTitle 设置为子视图,那么它将显示在该子视图中。当我们点击 Map Item 时,我需要这样 NavigationTitle 应该Map。当我们将导航标题应用于子项时,我无法找到错误为什么它不起作用。

任何帮助都应该感激。提前致谢。

4

1 回答 1

2

我找到了解决方案。

在这里我改变了我的HomePage

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. 它正在设置子视图的导航标题:

private extension HomePage {
    var navigationBarTitle: String {
        selectedTabbar ==  0 ? "Home" : "Map"
    }
}

使用这个扩展,我们可以将动态导航标题设置为TabView.

于 2021-01-03T04:38:27.410 回答