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);
相关推荐
开心就好20252 小时前
iOS App 安全加固流程记录,代码、资源与安装包保护
后端·ios
开心就好20252 小时前
iOS App 性能测试工具怎么选?使用克魔助手(Keymob)结合 Instruments 完成
后端·ios
zhongjiahao1 天前
面试常问的 RunLoop,到底在Loop什么?
ios
wvy2 天前
iOS 26手势返回到根页面时TabBar的动效问题
ios
RickeyBoy2 天前
iOS 图片取色完全指南:从像素格式到工程实践
ios
aiopencode3 天前
使用 Ipa Guard 命令行版本将 IPA 混淆接入自动化流程
后端·ios
二流小码农3 天前
鸿蒙开发:路由组件升级,支持页面一键创建
android·ios·harmonyos
iceiceiceice4 天前
iOS PDF阅读器段评实现:如何从 PDFSelection 精准还原一个自然段
前端·人工智能·ios
ssshooter5 天前
Tauri 踩坑 appLink 修改后闪退
前端·ios·rust
二流小码农5 天前
鸿蒙开发:上传一张参考图片便可实现页面功能
android·ios·harmonyos