UIImpactFeedbackGenerator失效?UIKit - Xcode13.4.1 - Swift5
解决触觉反馈无响应的问题
代码中的核心问题
你的HapticsManager里的haptic(for:)方法存在两个关键错误:
- 创建
UIImpactFeedbackGenerator时没有传入指定的FeedbackStyle参数,导致生成器始终使用默认样式,无法匹配你想要的振动强度 - 变量命名逻辑混淆(用了
notificationGenerator命名冲击反馈生成器),虽不影响运行但易引发后续维护问题
修正后的HapticsManager代码
import Foundation import UIKit final class HapticsManager{ static let shared = HapticsManager() private init(){} public func selectionVibrate(){ DispatchQueue.main.async { let selectionGenerator = UISelectionFeedbackGenerator() selectionGenerator.prepare() selectionGenerator.selectionChanged() } } public func impactHaptic(for style: UIImpactFeedbackGenerator.FeedbackStyle){ DispatchQueue.main.async { let impactGenerator = UIImpactFeedbackGenerator(style: style) impactGenerator.prepare() // 延迟触发给prepare留足初始化时间 DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) { impactGenerator.impactOccurred() } } } }
调用代码调整
按钮点击方法更新为调用修正后的方法:
@objc fileprivate func setButtonClicked(){ HapticsManager.shared.impactHaptic(for: .heavy) }
额外排查点
- 系统设置检查:确保设备「声音与触感」中的「系统触感反馈」已开启,静音模式振动开关也处于打开状态
- 设备兼容性:iPhone 6及更早机型不支持高级触觉反馈,仅能触发基础振动
- 按钮绑定验证:确认
addTargets()方法中已将按钮的.touchUpInside事件正确绑定到setButtonClicked()方法
内容的提问来源于stack exchange,提问作者iOSDeveloper
相关产品推荐
相关产品推荐

