如何在 SwiftUI 中同时使用 LongPressGesture 和 ScrollView 中的滚动?

问题描述 投票:0回答:1

让我们想象一下,这是一个带有一些元素的 ScrollView,我想通过长按这些元素来执行一些操作(例如改变颜色)。但我也想让滚动这个视图成为可能。

举个例子:

import SwiftUI

struct TextBox: View {
  var text: String
  var color: Color
  @GestureState private var isLongPressure: Bool = false
  
  var body: some View {
    let longTap = LongPressGesture(minimumDuration: 0.3)
      .updating($isLongPressure) { state, newState, transaction in
        newState = state
        transaction.animation = .easeOut(duration: 0.2)
      }
    
    Text(text)
      .frame(width: 400, height: 200)
      .background(isLongPressure ? .white : color)
      .simultaneousGesture(longTap)
  }
}

struct TestGestures: View {
    var body: some View {
      ScrollView {
        TextBox(text: "Test 1", color: .red)
        TextBox(text: "Test 2", color: .green)
        TextBox(text: "Test 3", color: .blue)
        TextBox(text: "Test 4", color: .red)
        TextBox(text: "Test 5", color: .green)
        TextBox(text: "Test 6", color: .blue)
      }
    }
}

struct TestGestures_Previews: PreviewProvider {
    static var previews: some View {
        TestGestures()
    }
}

所以,如果我评论 .simultaneousGesture(longTap) – 滚动有效,但如果我取消评论 – 滚动停止工作。

P.S.:我尝试在添加 longTap 之前添加 onTapGesture,但没有帮助。

提前致谢!

ios swift swiftui gesture tap
1个回答
0
投票

我不确定我是否理解确切的上下文,但您可以添加一个条件,以便您的 LongPressGesture 仅在手势未用于滚动时触发操作。

let longTap = LongPressGesture(minimumDuration: 0.3)
  .updating($isLongPressure) { value, state, transaction in
    if value == .ended {
      state = true
      transaction.animation = .easeOut(duration: 0.2)
    }
  }
© www.soinside.com 2019 - 2024. All rights reserved.