尝试在 TabView
中实现带有 PageTabView
样式的 SwiftUI
,其中导航仅以编程方式完成,并且所有滑动手势都被禁用。
This solution 仅部分有效 - 如果您在选择更改时点击屏幕,它仍然会干扰过渡并导致奇怪的效果。此外,如果您用两根手指滚动,手势仍然会记录。我需要一个完全禁用滑动手势的解决方案。
代码:
struct PageViewTest: View {
@State var selection: Int = 1
var body: some View {
ZStack {
Color.green.ignoresSafeArea()
TabView(selection: $selection) {
Color.red
.tag(1)
.gesture(DragGesture())
Color.blue
.tag(2)
.gesture(DragGesture())
Color.yellow
.tag(3)
.gesture(DragGesture())
}
.tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
.animation(.linear, value: selection)
VStack {
Spacer()
Button(action: {
selection = selection == 3 ? 1 : selection + 1
}) {
Text("next")
.foregroundColor(.white)
.font(.title)
}
}
}
}
}
将 .disabled(true)
设置为 TabView
可以解决问题,但是所有子视图都不再具有交互性。
答案 0 :(得分:0)
This answer 允许在 SwiftUI 中使用自定义手势识别器创建叠加层。 然后我们只需要创建一个不允许手势开始的委托。
所以代码是:
import SwiftUI
import UIKit
struct ContentView: View {
@State var selection: Int = 1
let numTabs = 3
let minDragTranslationForSwipe: CGFloat = 5000
var body: some View {
ZStack {
Color.green.ignoresSafeArea()
TabView(selection: $selection) {
Color.red
.tag(1)
Color.blue
.tag(2)
Color.yellow
.tag(3)
}
.tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
.animation(.linear, value: selection)
.overlay(TouchesHandler())
VStack {
Spacer()
Button(action: {
selection = selection == 3 ? 1 : selection + 1
}) {
Text("next")
.foregroundColor(.white)
.font(.title)
}
}
}
}
}
//just a dummy
class MySwipeGesture: UISwipeGestureRecognizer {
@objc func noop() {}
init(target: Any?) {
super.init(target: target, action: #selector(noop))
}
}
//this delegate effectively disables the gesure
class MySwipeGestureDelegate: NSObject, UIGestureRecognizerDelegate {
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
false
}
}
//and the overlay inspired by the answer from the link above
struct TouchesHandler: UIViewRepresentable {
func makeUIView(context: UIViewRepresentableContext<TouchesHandler>) -> UIView {
let view = UIView(frame: .zero)
view.isUserInteractionEnabled = true
view.addGestureRecognizer(context.coordinator.makeGesture())
return view;
}
func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<TouchesHandler>) {
}
func makeCoordinator() -> Coordinator {
return Coordinator()
}
class Coordinator {
var delegate: UIGestureRecognizerDelegate = MySwipeGestureDelegate()
func makeGesture() -> MySwipeGesture {
delegate = MySwipeGestureDelegate()
let gr = MySwipeGesture(target: self)
gr.delegate = delegate
return gr
}
}
typealias UIViewType = UIView
}