SwiftUI NavigationBar not disappearing while scrolling

Viewed 809

I want to hide my NavigationBar while scrolling, actually It must hide automatically but when I tried with multiple views It doesn't work. Also, It works when I remove custom views and capsulate List with NavigationView. But I need SearchBar and StatusView view. Is there any suggestion?

By the way, I run it on the device, I use canvas here for demonstration purposes.

Thank you.

var body: some View {
        NavigationView {
            VStack(spacing: 0) {
                SearchBar(searchText: $viewModel.searchText)
                StatusView(status: $viewModel.status)
                Divider()
                List(0...viewModel.characters.results.count, id: \.self) { index in
                    if index == self.viewModel.characters.results.count {
                        LastCell(vm: self.viewModel)
                    } else {
                        ZStack {
                            NavigationLink(destination: DetailView(detail: self.viewModel.characters.results[index])) {
                                EmptyView()
                            }.hidden()
                            CharacterCell(character: self.viewModel.characters.results[index])
                        }
                    }
                }
                .navigationBarTitle("Characters", displayMode: .large)
            }

        }
        .onAppear {
            self.viewModel.getCharacters()
        }
    }

image description

2 Answers

Just idea, scratchy... try to put your custom views inside List as below (I know it will work, but I'm not sure if autohiding will work)

NavigationView {
  List {
      SearchBar(searchText: $viewModel.searchText)
      StatusView(status: $viewModel.status)
      Divider()

      ForEach (0...viewModel.characters.results.count, id: \.self) { index in
      ...

Based on Asperi's solution, I wanted to have the SearchBar and StatusView always visible, i.e. it should stop scrolling after the title has disappeard. You can achieve this with a section header like shown below (just a rough sketch):

NavigationView {
    List {
        Section(header: {
            VStack {
                SearchBar...
                StatusView....
            }
        }) {
            ForEach...
        }
    }
}
Related