swiftswiftuihiddennavigationbar

How to animate navigationBarHidden in SwiftUI?


struct ContentView: View {
    @State var hideNavigationBar: Bool = false
    
    var body: some View {
        NavigationView {
            ScrollView {
                VStack {
                    Rectangle().fill(Color.red).frame(height: 50)
                        .onTapGesture(count: 1, perform: {
                            withAnimation {
                                self.hideNavigationBar.toggle()
                            }
                        })
                    VStack {
                        ForEach(1..<50) { index in
                            HStack {
                                Text("Sample Text")
                                Spacer()
                            }
                        }
                    }
                }
            }
            .navigationBarTitle("Browse")
            .navigationBarHidden(hideNavigationBar)
        }
    }
}

When you tap the red rectangle it snaps the navigation bar away. I thought withAnimation{} would fix this, but it doesn't. In UIKit you would do something like this navigationController?.setNavigationBarHidden(true, animated: true).

Tested in xCode 12 beta 6 and xCode 11.7


Solution

  • You could try using

    .navigationBarHidden(hideNavigationBar).animation(.linear(duration: 0.5)) instead of .navigationBarHidden(hideNavigationBar)

    and also move self.hideNavigationBar.toggle() out of the animation block. That is not required if you use the above approach for hiding of navigation bar with animation.