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);
相关推荐
openinstall11 小时前
A/B测试如何借力openinstall实现用户价值深挖?
android·ios·html
二流小码农11 小时前
鸿蒙开发:资讯项目实战之项目初始化搭建
android·ios·harmonyos
Hierifer16 小时前
跨端实现 DSBridge 源码解析
前端·ios
CocoaKier18 小时前
你的开发者账号已经被盯上了,如何区分钓鱼邮件
ios·google·apple
程序员小刘20 小时前
鸿蒙跨平台开发:打通安卓、iOS生态
android·ios·harmonyos
大熊猫侯佩21 小时前
SwiftUI 5.0(iOS 17.0,macOS 14.0+)新 Inspector 辅助视图之趣味漫谈
macos·ios·swiftui
二流小码农1 天前
鸿蒙开发:资讯项目实战之项目框架设计
android·ios·harmonyos
hepherd1 天前
Flutter - 原生交互 - 相机Camera - 曝光,缩放,录制视频
flutter·ios·dart
Android研究员2 天前
HarmonyOS实战:List拖拽位置交换的多种实现方式
android·ios·harmonyos
YungFan2 天前
Xcode26新特性与iOS26适配指南
ios·xcode