How to create haptic feedback for a Button in SwiftUI?

前端 未结 4 1981
伪装坚强ぢ
伪装坚强ぢ 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 23:12

    As I know, this is the most simplest way to get haptic feedback in SwiftUI

    When tapping a button :

    Button(action: {
        let impactMed = UIImpactFeedbackGenerator(style: .medium)
        impactMed.impactOccurred()
    }) {
        Text("This is a Button")
    }
    

    You can change the intensity of the haptic feedback by replacing .medium with .soft, .light, .heavy, or .rigid

    or when tapping anything else :

    .onTapGesture {
     let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
                impactHeavy.impactOccurred()
    }
    

    If you want to make something like Haptic Touch, replace .onTapGesture with .onLongPressGesture like this

    .onLongPressGesture {
     let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
                impactHeavy.impactOccurred()
    }
    

提交回复
热议问题