swift NavigationStack和TabView -未显示工具栏和标题

goucqfw6  于 2023-02-11  发布在  Swift
关注(0)|答案(1)|浏览(129)

我遇到了一个关于NavigationStack内部显示的TabView的问题。TabView包含多个视图。每个视图都有自己的navigationBarTitle和工具栏。问题是这些视图的工具栏和导航标题没有显示。只有视图内部定义的内容。我编写了以下代码:

struct Home : View {
 var body some : View {
      NavigationStack {
          TabView(selection: $router.currentTab) {
            First()
                .tag(0)
            
            Second()
                .tag(1)
            
            Third()
                .tag(2)
            
            Fourth()
                .tag(3)
            
            Fifth()
                .tag(4)
        }
    }
 }
}

First()视图定义如下(所有其他视图的结构类似):

struct First: View {
    
    var body: some View {
        ZStack {
            Color("background").ignoresSafeArea(.all)
            ScrollView {
                VStack(spacing: 15) {
                    
                    WhatsNewView()
                    
                    FavoriteView()
                    
                    Spacer()
                }
            }
            .refreshable {
                DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
                    newsService.getArticles()
                    simpleSuccess()
                }
            }
        }
        .toolbar {
            ToolbarItem(placement: .navigationBarTrailing) {
                UserButton()
            }
            
            ToolbarItem(placement: .navigationBarLeading) {
                ToolbarRanking()
            }
            
            ToolbarItem(placement: .navigationBarLeading) {
                ToolbarCalendar()
            }
            
            ToolbarItem(placement: .navigationBarLeading) {
                ToolbarSearch()
            }
        }
        .navigationBarTitle("Home")
    }
}

有人知道怎么解决这个问题吗?

h7appiyu

h7appiyu1#

TabView应该是您的顶级视图。
每个选项卡应包含自己的NavigationStack。例如

struct ContentView: View {
        
    var body: some View {
        TabView {
            NavigationStack {
                Text("first")
                    .navigationTitle("first")
            }
            .tabItem {
                Text("first")
            }
            NavigationStack {
                Text("second")
                    .navigationTitle("second")
            }
            .tabItem {
                Text("second")
            }
            NavigationStack {
                Text("third")
                    .navigationTitle("third")
            }
            .tabItem {
                Text("third")
            }
            NavigationStack {
                Text("fourth")
                    .navigationTitle("fourth")
            }
            .tabItem {
                Text("fourth")
            }

            NavigationStack {
                Text("fifth")
                    .navigationTitle("fifth")
            }
            .tabItem {
                Text("fifth")
            }
        }
    }
}

相关问题