Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Haptic Feedback Vibrations in SwiftUI
// This prints a list of buttons that on tap will fire a different type of haptic vibration
import SwiftUI
struct ContentView: View {
let generator = UINotificationFeedbackGenerator()
var body: some View {
VStack(alignment: .center, spacing: 30.0) {
Button(action: {
self.generator.notificationOccurred(.success)
}) {
Text("Notification - Success")
}
Button(action: {
self.generator.notificationOccurred(.error)
}) {
Text("Notification - Error")
}
Button(action: {
self.generator.notificationOccurred(.warning)
}) {
Text("Notification - Warning")
}
Button(action: {
let impactLight = UIImpactFeedbackGenerator(style: .light)
impactLight.impactOccurred()
}) {
Text("Impact - Light")
}
Button(action: {
let impactMed = UIImpactFeedbackGenerator(style: .medium)
impactMed.impactOccurred()
}) {
Text("Impact - Medium")
}
Button(action: {
let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
impactHeavy.impactOccurred()
}) {
Text("Impact - Heavy")
}
Button(action: {
let selectionFeedback = UISelectionFeedbackGenerator()
selectionFeedback.selectionChanged()
}) {
Text("Selection Feedback - Changed")
}
}
.padding(.all, 30.0)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
@USBA
Copy link

USBA commented Apr 29, 2020

To get "warning" haptic feedback, replace .error with . warning

Button(action: {
       self.generator.notificationOccurred(.warning)
 }) {
      Text("Notification - Warning") 
}

@Harry-Harrison
Copy link
Author

Harry-Harrison commented Apr 29, 2020

@USBA Good catch, fixed in the original 👍

@djrobby
Copy link

djrobby commented Jun 4, 2020

This is great! 👍

@Nuhanabilah
Copy link

Nuhanabilah commented Jul 5, 2020

This is great. works on me

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment