SwiftUI: how to handle BOTH tap & long press of button?

前端 未结 8 1205
刺人心
刺人心 2020-12-15 06:59

I have a button in SwiftUI and I would like to be able to have a different action for \"tap button\" (normal click/tap) and \"long press\".

Is that possible in Swift

8条回答
  •  时光取名叫无心
    2020-12-15 07:37

    Here is my implementation using a modifier:

    struct TapAndLongPressModifier: ViewModifier {
      @State private var isLongPressing = false
      let tapAction: (()->())
      let longPressAction: (()->())
      func body(content: Content) -> some View {
        content
          .scaleEffect(isLongPressing ? 0.95 : 1.0)
          .onLongPressGesture(minimumDuration: 1.0, pressing: { (isPressing) in
            withAnimation {
              isLongPressing = isPressing
              print(isPressing)
            }
          }, perform: {
            longPressAction()
          })
          .simultaneousGesture(
            TapGesture()
              .onEnded { _ in
                tapAction()
              }
          )
      }
    }
    

    Use it like this on any view:

    .modifier(TapAndLongPressModifier(tapAction: {  },
                                      longPressAction: {  }))
    

    It just mimics the look a button by scaling the view down a bit. You can put any other effect you want after scaleEffect to make it look how you want when pressed.

提交回复
热议问题