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);
相关推荐
麦客奥德彪12 小时前
客户端 Trace Benchmark 体系设计
ios·数据分析
Digitally20 小时前
6 种简易方法轻松连接 iPad 与电脑
ios·电脑·ipad
2501_915921431 天前
uni-app一键生成iOS安装包并上传TestFlight全流程
android·ios·小程序·https·uni-app·iphone·webview
sp42a1 天前
如何在 NativeScript 中使用 iOS 的 Metal 着色器
ios·着色器·nativescript
Mr_CrazyPeter2 天前
iONSPlayer 1.1.1版本发布
游戏·ios·模拟器
秋雨梧桐叶落莳2 天前
iOS——UI入门
ui·ios·cocoa
zhensherlock2 天前
Protocol Launcher 系列:Agenda 优雅组织你的想法与日程
javascript·macos·ios·typescript·node.js·mac·ipad
Rhys..2 天前
webdriveragent setup教程
ios
报错小能手2 天前
ios开发方向——swift内存基础
开发语言·ios·swift
SY.ZHOU2 天前
移动端架构体系(二):本地持久化与动态部署
flutter·ios·安卓