向下滚动时显示NavigationBar

时间:2020-08-02 13:26:41

标签: swift swiftui

我有一个带有隐藏的NavigationBar的简单代码,但是我想向下滚动时显示它。我该怎么办?

struct ContentView: View {
    
    var body: some View {
        NavigationView {
            ScrollView(showsIndicators: false) {
                VStack {
                    ForEach(0 ..< 3) { _ in
                        Image(systemName: "rectangle.fill")
                            .resizable()
                            .aspectRatio(contentMode: .fill)
                            .padding()
                    }
                }
            }
            .navigationBarTitle("Title Here", displayMode: .inline)
            .navigationBarHidden(true)
        }.edgesIgnoringSafeArea(.all)
    }
}

1 个答案:

答案 0 :(得分:1)

有可能,但是该修改器无法设置动画,因此条会立即显示(使用按钮切换条时会观察到同样的情况)。无论如何,我认为值得发布。

通过Xcode 12 / iOS 14测试

demo

struct ContentView: View {
    @State private var barHidden = true

    var body: some View {
        NavigationView {
            ScrollView(showsIndicators: false) {
                VStack {
                    ForEach(0 ..< 3) { _ in
                        Image(systemName: "rectangle.fill")
                            .resizable()
                            .aspectRatio(contentMode: .fill)
                            .padding()
                    }
                }.background(GeometryReader {
                    Color.clear.preference(key: ViewOffsetKey.self,
                        value: -$0.frame(in: .named("scroll")).origin.y)
                })
                .onPreferenceChange(ViewOffsetKey.self) {
                    if !barHidden && $0 < 50 {
                        barHidden = true
                        print("<< hiding")
                    } else if barHidden && $0 > 50{
                        barHidden = false
                        print(">> showing")
                    }
                }
            }.coordinateSpace(name: "scroll")
            .navigationBarTitle("Title Here", displayMode: .inline)
            .navigationBarHidden(barHidden)
        }
        .animation(.default, value: barHidden)
        .edgesIgnoringSafeArea(.all)
    }
}

struct ViewOffsetKey: PreferenceKey {
    typealias Value = CGFloat
    static var defaultValue = CGFloat.zero
    static func reduce(value: inout Value, nextValue: () -> Value) {
        value += nextValue()
    }
}