【问题标题】:How can I have 2 Gestures in SwiftUI?如何在 SwiftUI 中拥有 2 个手势?
【发布时间】:2021-02-07 03:57:04
【问题描述】:

我有一个可移动的 CircleView()!我希望此视图的 DragGesture 的 minimumDistance 为零,另一方面,我定义了另一个名为 onTapGesture 的手势,它正在工作,但不是我想要的方式!因为 onTapGesture 的 minimumDistance 变成了 10 并且通过拖动你可以看到 SwiftUI 认为 minimumDistance 是 10,我怎样才能让两个手势在 minimumDistance = 0 时都能正常工作?

我的目标:我想要一个onTapGesture和一个minimumDistance = 0

DragGesture
    import SwiftUI

struct ContentView: View {
    var body: some View {
        
        CircleView()
        
    }
}

struct CircleView: View {

    @State private var location: CGSize = CGSize()
    @GestureState private var translation: CGSize = CGSize()
    
    var body: some View {
        Circle()
            .fill()
            .frame(width: 100, height: 100, alignment: .center)
            .position(x: location.width + translation.width + 100, y: location.height + translation.height + 100)
   
            .onTapGesture { print("onTapGesture!") }                  // << Until here: minimumDistance: 10
            
            .gesture(DragGesture(minimumDistance: 0)                  // << After here: minimumDistance: 0 But also it does not Help! SwiftUI thinks that minimumDistance is 10!
                        .updating($translation) { value, state, _ in
                            state = value.translation
                        }
                        .onEnded { value in
                            location = CGSize(width: location.width + value.translation.width, height: location.height + value.translation.height)
                        })
        
    }
}

【问题讨论】:

  • 试试simultaneousGesture

标签: swiftui


【解决方案1】:

一种选择是组合两个同时手势,如下所示:

   import SwiftUI

struct ContentView: View {
  var body: some View {
    
    CircleView()
    
  }
}

struct CircleView: View {
  
  @State private var location: CGSize = CGSize()
  @GestureState private var translation: CGSize = CGSize()
  
  var body: some View {
    
    let tapDrag = DragGesture(minimumDistance: 0)
      .updating($translation) { value, state, _ in
        state = value.translation
      }
      .onEnded { value in
        location = CGSize(width: location.width + value.translation.width, height: location.height + value.translation.height)
      }
      .simultaneously(with: TapGesture()
                        .onEnded{ print("onTapGesture!") }  )
    
    Circle()
      .fill()
      .frame(width: 100, height: 100, alignment: .center)
      .position(x: location.width + translation.width + 100, y: location.height + translation.height + 100)
      .gesture(tapDrag)
  }
}

【讨论】:

    猜你喜欢
    • 2021-10-23
    • 2020-08-17
    • 2019-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-22
    • 2019-10-24
    • 1970-01-01
    相关资源
    最近更新 更多