SwiftUI TabView PageTabViewStyle 阻止更改选项卡?

人气:1,001 发布:2022-10-16 标签: ios swiftui swiftui-tabview

问题描述

我在 SwiftUI 的 PageViewTabStyle 中有一个 TabView,所以我可以在页面之间滑动.我想要一个锁定"设置当前视图就位,因此用户无法滑动.谷歌搜索和阅读文档对我来说没有任何明显的意义,所以我希望 SO 上的大师可以帮助我.

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())

我发现了 disabled 属性,但随后似乎整个视图上的所有点击事件都被忽略了 - 我只是想阻止用户切换标签(或者,在这种特殊情况下,滑动或按页面点可切换页面).我已经尝试了 here 中的解决方案,其中gesture 属性设置为 nil,但这似乎并没有真正阻止滑动手势改变页面(indexDisplayMode 位很好,不过!)

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!

推荐答案

上述参考作品中的解决方案,只是滑动不是被 gesture(nil) 阻止,而是被 gesture(DragGesture()).并且视图应该是全标签内容视图范围的,例如

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())

使用 Xcode 12.1/iOS 14.1 测试

Tested with Xcode 12.1 / iOS 14.1

* 当然,它可以像 https://stackoverflow.com/a/63170431 那样有条件/12299030

999