gpt4 book ai didi

ios - 在 SwiftUI TabView 中禁用滑动手势

转载 作者:行者123 更新时间:2023-12-05 06:50:15 24 4
gpt4 key购买 nike

尝试在 SwiftUI 中实现具有 PageTabView 样式的 TabView,其中导航仅以编程方式完成,并且禁用所有滑动手势。

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 可以解决它,但是所有的 subview 都不再具有交互性。

最佳答案

This answer允许在 SwiftUI 中使用自定义手势识别器创建叠加层。然后我们需要做的就是创建一个不允许手势开始的委托(delegate)。

所以代码是:

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
}

关于ios - 在 SwiftUI TabView 中禁用滑动手势,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66450760/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com