Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

swiftui

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

like image 292
Randy Avatar asked Oct 23 '25 17:10

Randy


2 Answers

For UIScrollView, there's a scrollsToTop property you can disable:

let scrollview = UIScrollView()
scrollview.scrollsToTop = false

Nothing for SwiftUI's ScrollView as far as I can tell. You could use UIViewRepresentable to wrap UIScrollView for SwiftUI.

like image 189
fer0n Avatar answered Oct 26 '25 07:10

fer0n


The accepted answer is wrong... As other have mentioned, you can disable that in UIKit using scrollToTop. While there is currently no way to control that directly using SwiftUI, you can use SwiftUI Introspect to get the underlying UIScrollView and set that property.

import SwiftUIIntrospect

ScrollView {
  // [...]
}
.introspect(.scrollView, on: .iOS(.v13, .v14, .v15, .v16, .v17, .v18)) { scrollView in
  scrollView.scrollsToTop = false
}

You should be wary of using SwiftUIIntrospect too much, but for specific use cases like that, it beats writing your own UIHostingController and using a UIScrollView directly.

like image 26
Gab Royer Avatar answered Oct 26 '25 06:10

Gab Royer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!