Haptics extension to UIViewController in Swift
If you want to add haptics to your application quickly, the code below is an extension to UIViewController that you can quickly add to your Xcode project, and then just as quickly yank it out if you’d like.
The ‘@obj’ allows you to target a function like hapticError() with a button touchUpInside, but you can also simply call the functions directly from your code.
Keep in mind that users may not learn the recognize numerous different types of haptic feedback. Consider limiting yourself to just two or three different types of haptic feedback. Or just one type of haptic feedback. Use haptics judiciously.
Here’s my UIViewController+Haptics.swift:
import UIKit
/// Look into calling generator.prepare()
/// https://developer.apple.com/documentation/uikit/uifeedbackgenerator
extension UIViewController {
@objc func hapticError() {
let generator = UINotificationFeedbackGenerator()
generator.notificationOccurred(.error)
}
@objc func hapticSuccess() {
let generator = UINotificationFeedbackGenerator()
generator.notificationOccurred(.success)
}
@objc func hapticWarning() {
let generator = UINotificationFeedbackGenerator()
generator.notificationOccurred(.warning)
}
@objc func hapticImpactLight() {
let generator = UIImpactFeedbackGenerator(style: .light)
generator.impactOccurred()
}
@objc func hapticImpactMedium() {
let generator = UIImpactFeedbackGenerator(style: .medium)
generator.impactOccurred()
}
@objc func hapticImpactHeavy() {
let generator = UIImpactFeedbackGenerator(style: .heavy)
generator.impactOccurred()
}
@objc func hapticSelectionChanged() {
let generator = UISelectionFeedbackGenerator()
generator.selectionChanged()
}
}
I use plain text because (a) it’s accessible, and (b) screenshots and/or color markup sure would be nice, but please refer back to (a).