SwiftUI - How to programatically scroll to top and show a large navigation title?

Viewed 564

Recently added to iOS 14 ScrollViewReader added a way to programmatically scroll to a view in SwiftUI.

Q: Is there a way to scroll past the topmost element in ScrollView and reveal a large navigation title?

Expected effect: Large navigation title after scrolling to top

Outcome: Inline navigation title after scrolling to top

Code snippet for reference:

import SwiftUI

struct ContentView: View {
  var body: some View {
    NavigationView {
      ScrollViewReader { proxy in
        ScrollView {
          Rectangle()
            .fill(.yellow)
            .aspectRatio(contentMode: .fit)
            .id("scrollID")
          Rectangle()
            .fill(.blue)
            .aspectRatio(contentMode: .fit)
          Rectangle()
            .fill(.green)
            .aspectRatio(contentMode: .fit)
          Rectangle()
            .fill(.red)
            .aspectRatio(contentMode: .fit)
          Button("Scroll to top") {
            withAnimation {
              proxy.scrollTo("scrollID")
            }
          }
        }
        .navigationTitle("Navigation")
      }
    }
  }
}

This code scrolls to a top rectangle on the button tap but it doesn't reveal the default large navigation title. How could I achieve that?

1 Answers

(I haven't tested it!) Try:

  1. declare state var to toggle navigation display mode
  2. add .navigationBarTitle("Home", displayMode: showLargeDisplayMode ? .large : .inline)
  3. toggle showLargeDisplayMode after proxy.scrollTo("scrollID")
Related