How to create haptic feedback for a Button in SwiftUI?

前端 未结 4 1987
伪装坚强ぢ
伪装坚强ぢ 2021-02-12 22:15

I\'m trying to implement haptic feedback at the beginning of a tap for a Button in SwiftUI. Therefore I\'m trying to use simultaneousGesture, but I\'m sill struggling. I can\'t

4条回答
  •  一生所求
    2021-02-12 22:50

    I have a wrapper view that plays a haptic event, and then calls the action:

    struct HapticButton: View {
      let content: String
      let action: () -> Void
    
      init(_ content: String, _ action: @escaping () -> Void) {
        self.content = content
        self.action = action
      }
    
      var body: some View {
        
        Button(content) {
            HapticService.shared.play(event: .buttonTap)
            self.action()
        }
      }
    }
    

    Used like:

    HapticButton("Press me") { print("hello") } // plays haptic and prints
    

提交回复
热议问题