Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI TabView PageTabViewStyle prevent changing tab?

I have a TabView in SwiftUI in the PageViewTabStyle so i can swipe from page to page. I'd like to have a setting that "locks" the current view in place, so the user cannot swipe. Googling and reading docs isn't turning up anything obvious for me, so I was hoping the gurus on SO could help me out.

In short, my code looks like

TabView {
   ForEach(0..<5) { idx in
      Text("Cell: \(idx)")
   }
}
.tabViewStyle(PageTabViewStyle())

I have found the disabled property, but then it appears that all tap events are ignored on the entire view - I just want to prevent the user from switching tabs (or, in this particular case, swiping or pressing the page dots to switch pages). I've tried the solution from here where the gesture property is set to nil, but that doesn't appear to actually stop the swipe gesture from changing the page (the indexDisplayMode bit was nice, though!)

Any help is greatly appreciated! Thanks!

like image 399
Hoopes Avatar asked Dec 31 '20 18:12

Hoopes


2 Answers

The solution from mentioned reference works, just the swipe is blocked not by gesture(nil), but by gesture(DragGesture()). And view should be full-tab-content-view-wide, like

    TabView {
      ForEach(0..<5) { idx in
        Text("Cell: \(idx)")
                .frame(maxWidth: .infinity, maxHeight: .infinity)
                .contentShape(Rectangle())
                .gesture(DragGesture())      // this blocks swipe
      }
    }
    .tabViewStyle(PageTabViewStyle())

Tested with Xcode 12.1 / iOS 14.1

* and, of course, it can be made conditional as in https://stackoverflow.com/a/63170431/12299030

like image 159
Asperi Avatar answered Nov 18 '22 23:11

Asperi


To block all the swipe gestures in a TabView you have to use .simultaneousGesture(DragGesture()) that blocks all the swipe gestures in the subviews as well

TabView {
          ForEach(0..<5) { idx in
            Text("Cell: \(idx)")
                    .frame(maxWidth: .infinity, maxHeight: .infinity)
                    .contentShape(Rectangle())
                    .simultaneousGesture(DragGesture())
          }
        }
        .tabViewStyle(PageTabViewStyle())
like image 45
Mohammed Shakeer Avatar answered Nov 19 '22 00:11

Mohammed Shakeer