iOS检测晃动/摇一摇功能实现文章来源:https://www.toymoban.com/news/detail-563523.html
app开发中,要实现检测晃动/摇一摇功能,下面记录下两种方案文章来源地址https://www.toymoban.com/news/detail-563523.html
方案一 利用UIAccelerometer加速器来检测
- (void)viewDidLoad
{
UIAccelerometer *accelerometer = [UIAccelerometer sharedAccelerometer];
accelerometer.delegate = self;
accelerometer.undateInterval = 1.0f / 60.0f;
}
- (void)accelerometer:(UIAccelerometer *)accelerometerdidAccelerate:(UIAcceletration *)acceleration
{
if(fabsf(acceleration.x)>2.0||fabsf(acceleration.y>2.0)||fabsf(acceleration.z)>2.0)
{
//NSLog(@"检测到晃动");
}
}
方案二 motion
// 第一步:在AppDelegate中设置如下:
- (BOOL)application:(UIApplication *)applicationdidFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
application.applicationSupportsShakeToEdit = YES;
}
// 第二步:在相应的viewController中添加相应的代码如下:
-(BOOL)canBecomeFirstResponder {
return YES;
}
-(void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[self becomeFirstResponder];
}
- (void)viewWillDisappear:(BOOL)animated {
[self resignFirstResponder];
[super viewWillDisappear:animated];
}
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent*)event
{
if (motion== UIEventSubtypeMotionShake) {
NSLog(@"检测到晃动");
}
}
到了这里,关于iOS开发 - 检测晃动/摇一摇功能UIAccelerometer与motion实现的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!