SwiftUI 在 NavigationView 中使用 tabview 自动折叠导航栏

时间:2021-07-14 07:35:47

标签: swiftui swiftui-navigationview swiftui-tabview swiftui-scrollview

我的代码具有类似于此处可见的结构。

import SwiftUI

struct ContentView: View {
    var body: some View {
        NavigationView {
            firstView()
        }
    }
}

struct firstView: View {
    var body: some View {
        NavigationLink(
            destination: secondView(),
            label: {
                Text("This is the first view")
            })
            .navigationTitle("First title")
        
    }
}

struct secondView: View {
    var body: some View {
        TabView {
            statsView()
                .tabItem { Text("StatsView") }
            secondStatsView()
                .tabItem { Text("SecondStatsView") }
        }
        .navigationBarTitle(Text("Second Title"))
    }
}

struct statsView: View {
    var body: some View {
        ScrollView {
            VStack {
                Rectangle()
                    .fill(Color.red)
                Rectangle()
                    .fill(Color.green)
                Rectangle()
                    .fill(Color.blue)
                Rectangle()
                    .fill(Color.red)
                Rectangle()
                    .fill(Color.green)
                Rectangle()
                    .fill(Color.blue)
                Rectangle()
                    .fill(Color.red)
                Rectangle()
                    .fill(Color.green)
                Rectangle()
                    .fill(Color.blue)
            }
        }
    }
}

struct secondStatsView: View {
    var body: some View {
        ScrollView {
            VStack {
                Rectangle()
                    .fill(Color.blue)
                Rectangle()
                    .fill(Color.green)
                Rectangle()
                    .fill(Color.red)
                Rectangle()
                    .fill(Color.blue)
                Rectangle()
                    .fill(Color.green)
                Rectangle()
                    .fill(Color.red)
                Rectangle()
                    .fill(Color.blue)
                Rectangle()
                    .fill(Color.green)
                Rectangle()
                    .fill(Color.red)
            }
        }
    }
}

TabView 位于 NavigationView 内部。两个 tabItems 都有滚动视图。在 statsView 上,NavigationBar 会自动关闭,但在 secondStatsView 上不会(参见 gif)。我想使用此代码构造,因为用户可以在应用程序的第一页上选择某些内容,选择后它将打开 tabview。用户可以从任何选项卡返回到 firstView。有没有办法克服这个问题?

enter image description here

0 个答案:

没有答案