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);
相关推荐
库奇噜啦呼1 天前
【iOS】NSOperation与NSOperationQueue
macos·ios·cocoa
二流小码农1 天前
鸿蒙开发:实现文本渐变效果
android·ios·harmonyos
WiresharkClub1 天前
抓包遇到私有协议全是乱码?抓包鹰自定义协议解码教程
ios
Lvan的前端笔记2 天前
ios:版本号和Build构建号
ios
鹤卿1232 天前
「iOS」3GShare总结
macos·ios·objective-c·cocoa
Lvan的前端笔记2 天前
ios:区分 App Store / Ad Hoc / Development
ios
Lvan的前端笔记2 天前
ios:证书配置
ios
FeliksLv2 天前
从 +load 到 Swift Macros:自动注册的演进与实践
ios·objective-c·swift
2501_915918413 天前
深入对比iOS开发中常用性能监控工具的底层原理与优缺点分析
android·ios·小程序·https·uni-app·iphone·webview
白玉cfc3 天前
【iOS】weak底层原理
macos·ios·cocoa