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);
相关推荐
鸿蒙布道师2 小时前
鸿蒙NEXT开发资源工具类(ArkTs)
android·ios·华为·harmonyos·arkts·鸿蒙系统·huawei
season_zhu4 小时前
iOS开发:关于路由
ios·架构·swift
鸿蒙布道师8 小时前
鸿蒙NEXT开发设备相关工具类(ArkTs)
android·ios·华为·harmonyos·arkts·鸿蒙系统·huawei
熊猫鹏-梓潼9 小时前
Swift Programming All in One苹果程序开发自学之路
开发语言·ios·swift
njsgcs18 小时前
用swift playground写个ios应用和大模型或者网站交互
ios·swift
leluckys1 天前
swift-11-init、deinit、可选链、协议、元类型
开发语言·ios·swift
njsgcs1 天前
vscode swift hello world
开发语言·ios·swift
YungFan1 天前
SwiftUI-MLX本地大模型开发(三)
ios·llm·swiftui
请叫我飞哥@1 天前
Apple ID授权登入
ios·swiftui
weixin_452093251 天前
关于apple ios苹果mdm监管锁的漏洞与修复
ios