1. AudioServicesPlaySystemSound
较早的系统版本,我们会使用AudioTool.framework
。
objectivec
#import <AudioToolbox/AudioToolbox.h>
一般震动
objectivec
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
普通短震(类似3D Touch的 Peek 反馈 )
objectivec
AudioServicesPlaySystemSound(1519);
普通短震 (类似3D Touch Pop 反馈)
objectivec
AudioServicesPlaySystemSound(1520);
连续三次短震
objectivec
AudioServicesPlaySystemSound(1521);
2. UIImpactFeedbackGenerator
iOS 10之后提供了UIImpactFeedbackGenerator
objectivec
@interface UIImpactFeedbackGenerator : UIFeedbackGenerator
- (instancetype)initWithStyle:(UIImpactFeedbackStyle)style;
// 调用后开始震动
- (void)impactOccurred;
// 调用后开始震动,强度从0~1
- (void)impactOccurredWithIntensity:(CGFloat)intensity API_AVAILABLE(ios(13.0));
@end
UIImpactFeedbackStyle
定义了震动的等级
objectivec
typedef NS_ENUM(NSInteger, UIImpactFeedbackStyle) {
UIImpactFeedbackStyleLight,
UIImpactFeedbackStyleMedium,
UIImpactFeedbackStyleHeavy,
UIImpactFeedbackStyleSoft API_AVAILABLE(ios(13.0)),
UIImpactFeedbackStyleRigid API_AVAILABLE(ios(13.0))
};
UIImpactFeedbackGenerator
使用
objectivec
UIImpactFeedbackGenerator *generator = [[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleLight];
[generator prepare];
[generator impactOccurred];