【问题标题】:SwiftUI drag gesture freezes with multi-touchSwiftUI 拖动手势冻结多点触控
【发布时间】:2020-11-13 09:39:36
【问题描述】:

我正在尝试在 SwiftUI 中拖动视图。

拖动效果很好,直到我将第二根手指放在屏幕上,之后拖动停止并且代码块(onChangedonEnded)都没有被调用。

但是,当我再次开始用单指拖动时,它又开始工作了。

有什么办法可以解决这个问题还是我遗漏了什么?

struct Pager: View {
  func drag(geometry: GeometryProxy) -> some Gesture {
    DragGesture()
    .onChanged({ (value) in
      //some code
    })
    .onEnded({ (value) in
      //some code
    })
  }

  var body: some View {
    GeometryReader { (geometry) in
      ZStack {
        ForEach(self.items.indices.reversed(), id: \.self) { index in
          Card(index: index, item: self.items[index])
            .offset(x: 0, y: self.offset(index: index, geometry: geometry))
            .animation(.linear)
        }
      }
      .background(Color.black)
      .gesture(self.drag(geometry: geometry))
    }
  }
}

【问题讨论】:

    标签: ios swiftui swift5 draggesture


    【解决方案1】:

    您可以使用与this post 相同的解决方案,因为我相信这是相同的根本问题。该解决方案采用 GestureState,它(如链接帖子中所述)是一个临时值,并在手势完成/中断时返回到其初始状态 (0, 0)。

    在使用 GestureState 时,您的代码应该如下所示(尽管您可以调整它以使用单独的拖动方法,如原始帖子中所示):

    struct Pager: View {
      @GestureState private var dragPosition = CGSize.zero
    
      var body: some View {
          ZStack {
            ForEach(self.items.indices.reversed(), id: \.self) { index in
              Card(index: index, item: self.items[index])
                .offset(x: 0, y: self.dragPosition.height) // This will now map the y offset of the card to the dragPosition GestureState. If you want the x offset use self.dragPosition.width
                .animation(.linear)
            }
          }
          .background(Color.black)
          .gesture(
              DragGesture()
                 .updating($dragPosition) { (value, gestureState, transaction) in
                     gestureState = CGSize(width: value.location.x - value.startLocation.x, height: value.location.y - value.startLocation.y)
                  }
                  .onChanged { value in
                      print("I'm changing")
                  }
                  .onEnded { value in
                      print("I've ended")
                  }
          )
        }
    }
    

    【讨论】:

      【解决方案2】:

      这种方法非常有用:

      Detect DragGesture cancelation in SwiftUI

      因此,基本上,您可以使用捏合和旋转手势组合拖动手势(同时使用 .simultaneously 组合它们)。

      当触发捏合或旋转时,您可以使用它来发出取消拖动手势的信号并相应地更新您的状态

      【讨论】:

        猜你喜欢
        • 2020-08-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多