iOS 添加震动效果

1. AudioServicesPlaySystemSound

较早的系统版本,我们会使用AudioTool.framework

#import <AudioToolbox/AudioToolbox.h>

一般震动

AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);

普通短震(类似3D Touch的 Peek 反馈 )

AudioServicesPlaySystemSound(1519);

普通短震 (类似3D Touch Pop 反馈)

AudioServicesPlaySystemSound(1520);

连续三次短震

AudioServicesPlaySystemSound(1521);

2. UIImpactFeedbackGenerator

iOS 10之后提供了UIImpactFeedbackGenerator

@interface UIImpactFeedbackGenerator : UIFeedbackGenerator

- (instancetype)initWithStyle:(UIImpactFeedbackStyle)style;

// 调用后开始震动
- (void)impactOccurred;

// 调用后开始震动,强度从0~1
- (void)impactOccurredWithIntensity:(CGFloat)intensity API_AVAILABLE(ios(13.0));

@end

UIImpactFeedbackStyle定义了震动的等级

typedef NS_ENUM(NSInteger, UIImpactFeedbackStyle) {
    UIImpactFeedbackStyleLight,
    UIImpactFeedbackStyleMedium,
    UIImpactFeedbackStyleHeavy,
    UIImpactFeedbackStyleSoft     API_AVAILABLE(ios(13.0)),
    UIImpactFeedbackStyleRigid    API_AVAILABLE(ios(13.0))
};

UIImpactFeedbackGenerator使用

UIImpactFeedbackGenerator *generator = [[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleLight];
[generator prepare];
[generator impactOccurred];