iOS 添加震动效果

开发过程中,有时候会碰到点击按钮或者某个动画会配合震动效果;
下面介绍iOS开发过程中的震动添加:

导入:#import <AudioToolbox/AudioToolbox.h>

在需要出发震动的地方写上代码:
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);//默认震动效果

如果想要其他震动效果,可参考:
// 普通短震,3D Touch 中 Pop 震动反馈
AudioServicesPlaySystemSound(1520);

// 普通短震,3D Touch 中 Peek 震动反馈
AudioServicesPlaySystemSound(1519);

// 连续三次短震
AudioServicesPlaySystemSound(1521);

另外 ios10 后加入的 UIImpactFeedbackGenerator ,提供了更好的震动效果。

调用也很简单:


UIImpactFeedbackGenerator*impactLight = [[UIImpactFeedbackGeneratoralloc]initWithStyle:UIImpactFeedbackStyleLight]; 
[impactLight impactOccurred];

震动有多个模式可选。


typedefNS_ENUM(NSInteger, UIImpactFeedbackStyle) {

    UIImpactFeedbackStyleLight,

    UIImpactFeedbackStyleMedium,

    UIImpactFeedbackStyleHeavy

};

注意:UIImpactFeedbackGenerator 只在 iphone7 后手机才会产生震动。


参考:

https://www.jianshu.com/p/064c225efb0f

https://www.jianshu.com/p/d1f5b4ec3a1d

原文地址:https://www.cnblogs.com/yang-shuai/p/10945056.html