我在 SwiftUI 应用程序中使用 Tab View。我想要更改页面disabled,同时向左或向右滑动。我从this实现了它。这工作正常,但我面临的问题是我在每个视图的 bottom 上都有一个 button,当我尝试从按钮上滑动时,它是 swiping 左右。我也想禁用它,但不知道该怎么做。这是我的代码:
struct TabViewTesting: View {
@State var tabSelection = 0
var body: some View {
TabView(selection: $tabSelection) {
firstView().tag(0).contentShape(Rectangle()).gesture(DragGesture())
secondView().tag(1).contentShape(Rectangle()).gesture(DragGesture())
thirdView().tag(2).contentShape(Rectangle()).gesture(DragGesture())
}.tabViewStyle(.page(indexDisplayMode: .never))
}
}
这是Views的代码:
extension TabViewTesting {
func firstView() -> some View {
VStack {
Text("First screen")
Spacer()
Button {
self.tabSelection = 1
} label: {
ZStack {
RoundedRectangle(cornerRadius: 20)
.frame(height: 50)
Text("move to 2nd view")
.foregroundColor(.white)
}
}.padding()
}.background(.green)
}
func secondView() -> some View {
VStack {
Text("second screen")
Spacer()
Button {
self.tabSelection = 2
} label: {
ZStack {
RoundedRectangle(cornerRadius: 20)
.frame(height: 50)
Text("move to 3rd view")
.foregroundColor(.white)
}
}.padding()
}.background(.red)
}
func thirdView() -> some View {
VStack {
Text("Third screen")
Spacer()
Button {
self.tabSelection = 0
} label: {
ZStack {
RoundedRectangle(cornerRadius: 20)
.frame(height: 50)
Text("move to first view")
.foregroundColor(.white)
}
}.padding()
}.background(.yellow)
}
}
这就是发生的事情:
我实际上在这个问题的评论中找到了答案。
问题是:任何具有“onTapGesture”的视图都会忽略“.gesture(DragGesture())”。
解决方案是使用“.simulataneousGesture(DragGesture())”来确保手势由视图/修改器捕获和处理。
更改后,它在我的情况下工作得很好。 唯一的例外是 2 指拖动手势。
在TabView末尾使用这行代码:
.gesture(DragGesture().onChanged({ _ in })).disabled(true)
在您的代码中像这样:
struct TabViewTesting: View {
@State var tabSelection = 0
var body: some View {
TabView(selection: $tabSelection) {
firstView().tag(0)
secondView().tag(1)
thirdView().tag(2)
}
.tabViewStyle(.page(indexDisplayMode: .never))
.gesture(DragGesture().onChanged({ _ in })).disabled(true)
}
}