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);
相关推荐
2501_9159214334 分钟前
VSCode 写 Swift 运行到 iPhone?快蝎 IDE 开发实战体验
ide·vscode·ios·objective-c·个人开发·swift·敏捷流程
spencer_tseng1 小时前
anti-screenshot (Android + iOS)
android·ios
2501_915918411 小时前
基于Mach-O文件的动态库与静态库归属方案及API扫描实践
android·ios·小程序·https·uni-app·iphone·webview
2501_915106321 小时前
iOS 证书无法跨电脑使用?签名迁移方法一文讲透
android·ios·小程序·https·uni-app·iphone·webview
WeirdoPrincess2 小时前
iOS 打包签名资料准备指南(HBuilderX / uni-app)
ios·uni-app
for_ever_love__2 小时前
Objective-C学习: OC方法调用的本质
开发语言·学习·ios·objective-c
RickeyBoy15 小时前
独立 App 配置阿里云 CDN 记录
ios
白玉cfc18 小时前
接口与API设计
ios·objective-c
少云清1 天前
IOS历史版本下载
ios
奶糖的次元空间2 天前
iOS 学习笔记 - SwiftUI 和 简单布局
ios·swift