How to create haptic feedback for a Button in SwiftUI?

前端 未结 4 1979
伪装坚强ぢ
伪装坚强ぢ 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:55

    You can use UIFeedbackGenerator like this:

    let generator = UINotificationFeedbackGenerator()
    generator.notificationOccurred(.error)
    

    Or, as you're using SwiftUI, you'll be able to use CoreHaptics like this:

    let engine = try CHHapticEngine()
    try engine.start()
    
    let hapticEvent = CHHapticEvent(eventType: .hapticTransient, parameters: [
        CHHapticEventParameter(parameterID: .hapticSharpness, value: sharpness), CHHapticEventParameter(parameterID: .hapticIntensity, value: intensity),
    ], relativeTime: 0)
    let audioEvent = CHHapticEvent(eventType: .audioContinuous, parameters: [
        CHHapticEventParameter(parameterID: .audioVolume, value: volume),
        CHHapticEventParameter(parameterID: .decayTime, value: decay),
        CHHapticEventParameter(parameterID: .sustained, value: 0),
    ], relativeTime: 0)
    
    let pattern = try CHHapticPattern(events: [hapticEvent, audioEvent], parameters: [])
    let hapticPlayer = try engine.makePlayer(with: pattern)
    try hapticPlayer?.start(atTime: CHHapticTimeImmediate)
    

提交回复
热议问题