简单触感是 Core Haptics
的一个便捷封装,使其更容易触发瞬时触感点击,类似于 UIFeedbackGenerator
。
import SimpleHaptics
let haptics = SimpleHapticGenerator()
try? haptics.fire(intensity: 0.5, sharpness: 1)
简单触感与 @Environment
集成良好。 您可以创建一个单独的 SimpleHapticGenerator
并将其作为环境对象传递到您的根 SwiftUI 视图,然后在任何需要触感反馈的子视图中使用它。 这样可以避免不必要地初始化大量 CHHapticEngine
,并允许您在应用程序生命周期事件中停止和启动触感引擎。 例如,在您的 SceneDelegate
中
import SimpleHaptics
import SwiftUI
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
let haptics = SimpleHapticGenerator()
...
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
let contentView = ContentView()
.environmentObject(haptics) // Pass your haptic generator into your root View.
...
// Be sure to stop the haptic generator when entering the background.
func sceneDidEnterBackground(_ scene: UIScene) {
haptics.stop()
}
func sceneWillEnterForeground(_ scene: UIScene) {
try? haptics.start()
}
}
然后,子视图只需创建正确类型的 @EnvironmentObject
变量即可使用它
import SimpleHaptics
import SwiftUI
struct MyView: View {
@EnvironmentObject private var haptics: SimpleHapticGenerator
...
}
dependencies: [
.package(url: "https://github.com/hallee/simple-haptics", from: "0.0.2")
],
targets: [
.target(name: "YourTarget", dependencies: ["SimpleHaptics"])
]