Search code examples
swiftswiftui

SwiftUI: Disable ScrollView scrolling to top if top of screen is touched


I have a UI which resides in a VStack{} with a custom topbar and a ScrollView. I have buttons on my top bar which do things like open user account details. I find that if I press some of these buttons the ScrollView autoscrolls to the top of the screen. Is there a way to stop that?

My code:

struct MyView: View {
    var body: some View {
        VStack(spacing:0) {
            TopBarView()
            ScrollView(.vertical) {
                ForEach(0..<100, id: \.self) { index in
                    Text(String(index))
                }
            }
        }
    }
    
    struct TopBarView: View {
        var body: some View {
            Text("This is a top bar")
        }
    }
}

If I touch the top of the screen above the scrollView's frame, the scrollView scrolls all the way to the top. Is there a way to disable that behavior?

GIF showing the behavior


Solution

  • This is not a SwiftUI or Xcode or ScrollView problem.

    This is a built-in feature of iPhone.

    When you tap the top-center edge of the screen, displayed contents will be scrolled up.

    Try opening apps like Facebook, WhatsApp, then scroll and tap at the same position, you will see the displayed contents scroll up.