iOS 按钮添加点击震动

1. 方法说明:

iOS10后系统提供了一套API来简单实现震动:

init时传入一个style定义好的枚举就可以实现不同的震动

c 复制代码
typedef NS_ENUM(NSInteger, UIImpactFeedbackStyle) {
    UIImpactFeedbackStyleLight,
    UIImpactFeedbackStyleMedium,
    UIImpactFeedbackStyleHeavy,
    UIImpactFeedbackStyleSoft     API_AVAILABLE(ios(13.0)),
    UIImpactFeedbackStyleRigid    API_AVAILABLE(ios(13.0))
};

// UIImpactFeedbackGenerator is used to give user feedback when an impact between UI elements occurs
UIKIT_EXTERN API_AVAILABLE(ios(10.0)) API_UNAVAILABLE(visionos) API_UNAVAILABLE(tvos, watchos) NS_SWIFT_UI_ACTOR
@interface UIImpactFeedbackGenerator : UIFeedbackGenerator

- (instancetype)initWithStyle:(UIImpactFeedbackStyle)style;

/// call when your UI element impacts something else
- (void)impactOccurred;

/// call when your UI element impacts something else with a specific intensity [0.0, 1.0]
- (void)impactOccurredWithIntensity:(CGFloat)intensity API_AVAILABLE(ios(13.0));

@end

2. 举例

c 复制代码
UIImpactFeedbackGenerator *generator = [[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleLight];
[generator impactOccurred];

3. 还有一套API

在AudioTool.framework里还有一套API可以实现震动,这个系统适配多些

c 复制代码
#import <AudioToolbox/AudioToolbox.h>
// 类似于老系统来短信的震动
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
// 类似touch一次短震
AudioServicesPlaySystemSound(1519);
// 类似touch长按app图标时的震动
AudioServicesPlaySystemSound(1520);
// 类似关iPhone左侧物理静音键的震动
AudioServicesPlaySystemSound(1521);
相关推荐
CocoaKier9 小时前
苹果开发者注意,请在2027年1月31日前完成合规验证,否则中国区可能下架
ios·aigc·apple
二流小码农13 小时前
鸿蒙开发:证书只能创建3个,第4个应用怎么办
android·ios·harmonyos
bcbnb13 小时前
Windows 上 iOS 开发接 CI,KXBuild 自托管 runner 出签名 ipa
后端·ios
疯华整猫20 小时前
别再抄 Flutter 了:2026 年 Android / iOS / 小程序跨端架构选型的四本成本账
android·前端·ios
黑科技iOS上架20 小时前
iOS游戏换皮上架困境:4.3同质化拒审
人工智能·ios·审核
黑科技iOS上架20 小时前
iOS二次开发应用上架难题:4.3a同质化拒审
ios·审核
传奇开心果编程20 小时前
【Flutter踩坑排雷】第30课:异常未捕获坑|未捕获异常直接闪退,全局兜底故障处理
android·flutter·ios·移动开发·dart·ui框架·声明式ui
茶底世界之下20 小时前
海边游乐场的黄昏:用 Awaking 留住一层暖光
ios·app·产品
90后的晨仔1 天前
Xcode 27.1 下,老工程如何在 iPhone Duo 模拟器上跑起来
ios
90后的晨仔1 天前
Xcode 27 升级后满屏 deployment target 报错?一文搞定
ios