如何在 SwiftUI 中拥有 2 个手势?

Posted

技术标签:

【中文标题】如何在 SwiftUI 中拥有 2 个手势?【英文标题】:How can I have 2 Gestures in SwiftUI? 【发布时间】: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 【参考方案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)
  

【讨论】:

以上是关于如何在 SwiftUI 中拥有 2 个手势?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Swift UIKit Map 组件中处理 SwiftUI 中的触摸手势?

在 SwiftUI 中,如何使手势在容器视图之外处于非活动状态?

SwiftUI手势(Gesture)进阶 : 实现任意视图的长按惯性加速行为

SwiftUI手势(Gesture)进阶 : 实现任意视图的长按惯性加速行为

SwiftUI手势(Gesture)进阶 : 实现任意视图的长按惯性加速行为

如何在swift / SwiftUI中为滑动手势设置菜单栏图标的操作