Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable vertical scroll in TabView with SwiftUI?

I have set up a TabView in my application, so that I can swipe horizontally between multiple pages, but I also have an unwanted vertical scroll that may appear, with a bounce effect so. How can I disable this vertical scroll?

My code:


struct ContentView: View {
  @State private var currentTabIndex: Double = 0

  var body: some View {
    VStack {
      TabView(selection: $currentTabIndex) {
        Text("Text n°1")
          .tag(0)
        
        Text("Text n°2")
          .tag(1)
      }
      .border(Color.black)
      .tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
    }
  }
}
like image 315
Guillaume Avatar asked Sep 07 '25 14:09

Guillaume


2 Answers

I had this same problem. It's not an exact solution, but you can turn off bouncing on scrollviews (which is used within a TabView). And as long as the items within the TabView are not larger than the TabView frame, it should act as if you disabled vertical scrolling.

I would call it either .onAppear or in your init function:

.onAppear(perform: {
   UIScrollView.appearance().bounces = false
 })

Note: this disables the bouncing on ALL scrollviews across your app... So you may want to re-enable it .onDisappear.

like image 54
nicksarno Avatar answered Sep 10 '25 14:09

nicksarno


Still an issue with Xcode 12.4.

I managed to workaround that by wrapping the TabView within a ScrollView and using the alwaysBounceVertical property set to false, as follow:

ScrollView(.horizontal) {
    TabView {
        ///your content goes here
    }
    .tabViewStyle(PageTabViewStyle())
}
.onAppear(perform: {
    UIScrollView.appearance().alwaysBounceVertical = false
})
.onDisappear(perform: {
    UIScrollView.appearance().alwaysBounceVertical = true
})
like image 29
valvoline Avatar answered Sep 10 '25 13:09

valvoline