IOS 摇一摇功能

本文介绍了两种用于检测iOS设备摇动的方法。方法一利用UIKit框架的内置功能实现,适用于大幅度摇动;方法二通过Core Motion框架监测加速度变化,可根据需要调整灵敏度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

设备摇动检测的两种方法简单的记录下


方法一

首先在delegate中添加

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

// Override point for customization after application launch

//添加检测晃动

application.applicationSupportsShakeToEdit = YES;

}


其次在需要检测的ViewController中添加


//检测手机晃动

-(BOOL)canBecomeFirstResponder

{

return YES;

}


- (void)viewWillDisappear:(BOOL)animated {

[self resignFirstResponder];

[super viewWillDisappear:animated];

}


- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event

{

if (motion == UIEventSubtypeMotionShake)

{

UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"恭喜你获得100-5优惠劵一张" delegate:self cancelButtonTitle:@"关闭" otherButtonTitles: nil];

[alertView show];

NSLog(@"检测到晃动");

}

}


-(void)prarGotProblem:(NSString *)problemTitle withDetails:(NSString *)problemDetails

{

[self alert:problemTitle withDetails:problemDetails];

}


方法二使用CoreMotion


引入需要的头文件

#import 


下需要检测的 viewDidLoad初始化CMMotionManager 同时启动一个NSTimer检测X、Y、Z轴的变化


- (void)viewDidLoad {

[super viewDidLoad];

// Do any additional setup after loading the view.

NSTimer *AutoTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/60.0 target:self selector:@selector(autoChange) userInfo:nil repeats:YES];


_manager = [[CMMotionManager alloc]init];

_manager.accelerometerUpdateInterval=1.0/60.0;

[_manager startAccelerometerUpdates];

}

-(void)autoChange

{

//根据自己需求调节x y z

if (fabsf(_manager.accelerometerData.acceleration.x) > 1.0 || fabsf(_manager.accelerometerData.acceleration.y) > 1.2 || fabsf(_manager.accelerometerData.acceleration.z) > 0.5)

{

NSLog(@"我晃动了 。。。。。");

}

}



注:方法一中晃动幅度大的情况下才会调用,方法二中可以根据自己的需要调节
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值