繁体   English   中英

SwiftUI ScrollView 和 OnLongPressGesture

[英]SwiftUI ScrollView and OnLongPressGesture

当我按住 Rectangle 时,我会播放一段视频。 当 onLongPressGesture function 处于活动状态时,我无法滚动矩形。 我可以滚动浏览两个矩形之间的空间。 好像 onLongPressGesture 优先考虑自己。 如何在 ScrollView 中运行 onLongPressGesture 而没有任何问题?

代码:

ScrollView(.horizontal) {
    HStack {
        ForEach(0 ..< 15) { item in
            RoundedRectangle(cornerRadius: 25.0)
                .frame(width: 125, height: 200)
                .padding(.horizontal)
                .onLongPressGesture {
                    self.videoStatus.isStartVideo = true
                }
        }
    }
}

在此处输入图像描述

您可以创建一个UIViewRepresentable并将一个UILongPressGestureRecognizer附加到它:

struct GestureView: UIViewRepresentable {
    let callback: () -> Void

    func makeUIView(context: UIViewRepresentableContext<GestureView>) -> UIView {
        let view = UIView(frame: .zero)
        let gesture = UILongPressGestureRecognizer(target: context.coordinator, action: #selector(context.coordinator.action))
        gesture.delegate = context.coordinator
        gesture.cancelsTouchesInView = false
        view.addGestureRecognizer(gesture)
        return view
    }

    func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<GestureView>) {}

    class Coordinator: NSObject {
        let callback: () -> Void

        init(callback: @escaping () -> Void) {
            self.callback = callback
        }

        @objc func action(_ sender: UIPanGestureRecognizer) {
            if sender.state == .began {
                callback()
            }
        }
    }

    func makeCoordinator() -> GestureView.Coordinator {
        Coordinator(callback: callback)
    }
}

extension GestureView.Coordinator: UIGestureRecognizerDelegate {
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        true
    }
}

例如,您可以将此视图用作overlay

struct ContentView: View {
    var body: some View {
        ScrollView(.horizontal) {
            HStack {
                ForEach(0 ..< 15) { item in
                    RoundedRectangle(cornerRadius: 25.0)
                        .frame(width: 125, height: 200)
                        .padding(.horizontal)
                        .overlay(GestureView(callback: { print("callback") }))
                }
            }
        }
    }
}

.onTapGesture { } .onLongPressGesture{ }

所以,你的代码会喜欢:

ScrollView(.horizontal) {
HStack {
    ForEach(0 ..< 15) { item in
        RoundedRectangle(cornerRadius: 25.0)
            .frame(width: 125, height: 200)
            .padding(.horizontal)
            .onTapGesture {  }
            .onLongPressGesture {
                self.videoStatus.isStartVideo = true
            }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM