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);
相关推荐
林大鹏天地4 分钟前
使用Xcode16打包后,App在暗夜模式下,iOS18 切换Tabbar的item,会有一根白色线条闪过。
ios
2501_9159090612 分钟前
iOS 加固工具实战解析,主流平台审核机制与工具应对策略
android·ios·小程序·https·uni-app·iphone·webview
2501_915106322 小时前
iOS WebView 调试实战,第三方脚本加载失败与内容安全策略冲突问题排查指南
android·ios·小程序·https·uni-app·iphone·webview
笑尘pyrotechnic14 小时前
DocC的简单使用
ios·objective-c
谈吐大方的鹏sir16 小时前
SwiftUI-Text组件学习
ios
不自律的笨鸟17 小时前
iOS 26,双版本更新来了
ios·iphone
归辞...1 天前
「iOS」————消息传递和消息转发
ios
他们都不看好你,偏偏你最不争气1 天前
iOS —— 天气预报仿写总结
ios
白玉cfc2 天前
【iOS】网易云仿写
ui·ios·objective-c
归辞...2 天前
「iOS」——内存五大分区
macos·ios·cocoa