Curnelious
Curnelious

Reputation: 1

Setup custom Haptic with latest Swift for iPhone7 and up

After reading about it, I have some mess in my head.

This function is being called while user swipe his finger on some UI element :

func wasDragged() { signal here }

I would like to make small Haptic signals every time it's being called ( like a dates picker wheel )

  1. How would I setup first time and make the signals of the Haptic Engine on call ?
  2. Do I have to check for device kind ? I want it only on iPhone 7 and up.

Using latest Swift.

Upvotes: 0

Views: 267

Answers (1)

inokey
inokey

Reputation: 6170

The documentation oh Haptic feedback is really descriptive. But if you want some quick solution here it is.

var hapticGenerator: UISelectionFeedbackGenerator?

func wasDragged() {

    hapticGenerator = UISelectionFeedbackGenerator()
    haptiGenerator.selectionChanged()
    hapticGeneraor = nil

}

Alternatively depending on the logic of the screen, you can initialize generator outside of wasDragged function and inside of it just call hapticGenerator.prepare() and selectionChanged(). In that case you should not assign nil to it after the dragging is complete because it won't get triggered again. As per documentation you have to release generator when no longer needed as Taptic Engine will wait and therefore consume system resources for another call.

Note that calling these methods does not play haptics directly. Instead, it informs the system of the event. The system then determines whether to play the haptics based on the device, the application’s state, the amount of battery power remaining, and other factors.

For example, haptic feedback is currently played only:

  • On a device with a supported Taptic Engine
  • When the app is running in the foreground
  • When the System Haptics setting is enabled

Documentation:

https://developer.apple.com/documentation/uikit/uifeedbackgenerator

Upvotes: 1

Related Questions