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);
相关推荐
会Tk矩阵群控的小木10 分钟前
企业级iMessage群发系统实战:单主机管控多iPhone设备完整实现
运维·ios·开源软件·个人开发
人月神话-Lee1 小时前
【图像处理】vImage/Accelerate——SIMD 让 CPU 也能飞
图像处理·深度学习·ios·cnn·ai编程·swift
万能小林子1 小时前
如何将网页在线转APP?5种打包工具对比速成指南(含在线/手机/电脑方案)
android·ios·uni-app·web app·wap2app·app打包·app封装
2601_955767422 小时前
iPhone 17屏幕反光怎么解?磁控溅射AR膜实测反射率低至0.5%
ios·ar·iphone·#观复盾护景贴·scinique双护技术
盼小辉丶3 小时前
PyTorch深度学习实战(56)——在iOS上构建PyTorch应用
pytorch·深度学习·ios
for_ever_love__12 小时前
UI学习:UISearchController基础了解和应用
学习·ui·ios·objective-c
代码的小搬运工16 小时前
ZARA仿写
ios
人月神话Lee18 小时前
【图像处理】vImage/Accelerate——SIMD 让 CPU 也能飞
ios·swift·图像识别
2601_955767421 天前
iPhone 17 护眼钢化膜怎么选?从PWM频闪到圆偏振光,解析「软硬协同」光学方案
ios·ar·iphone·护眼钢化膜·圆偏振光·#观复盾护景贴·磁控溅射
2601_955767421 天前
iPhone 17 护眼保护膜怎么选?圆偏振光 + AR 抗眩方案,解读 96% 透光率与 ≤0.5% 反射率的协同价值
ios·ar·iphone·圆偏振光·#观复盾护景贴·scinique双护技术