iOS開發搖動手勢實現詳解


1.當設備搖動時,系統會算出加速計的值,並告知是否發生了搖動手勢。系統只會運動開始和結束時通知你,並不會在運動發生的整個過程中始終向你報告每一次運動。例如,你快速搖動設備三次,那只會收到一個搖動事件。

2,想要實現搖動手勢,首先需要使視圖控制器成為第一響應者,注意不是單獨的控件。成為第一響應者最恰當的時機是在視圖出現的時候,而在視圖消失的時候釋放第一響應者。

-(BOOL)canBecomeFirstResponder
{
    return YES;
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self becomeFirstResponder];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [self resignFirstResponder];
    [super viewWillDisappear:animated];
}

 

現在,視圖控制器准備處理運動事件,其中有三個方法,motionBegan,motionEnded和motionCancelled,這些與觸摸方法有着相似的工作原理,但沒有移動方法。

 

- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    if (event.type == UIEventSubtypeMotionShake)
    {
        NSLog(@"Shake Began");
    }
}

-(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    if (event.type == UIEventSubtypeMotionShake)
    {
        NSLog(@"Shake End");
    }
}

-(void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    if (event.type == UIEventSubtypeMotionShake)
    {
        NSLog(@"Shake Cancelled");
    }
}

 以上是轉載自http://blog.csdn.net/marvindev

我的代碼:

//
//  ocqViewController.m
//  shake
//
//  Created by ocq on 14-4-29.
//  Copyright (c) 2014年 ocq. All rights reserved.
//

#import "ocqViewController.h"

@interface ocqViewController ()

@end

@implementation ocqViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSLog(@"初始化了實例");
	// Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(BOOL)canBecomeFirstResponder
{
    return YES;
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self becomeFirstResponder];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [self resignFirstResponder];
    [super viewWillDisappear:animated];
}

////當手機移動結束時調用該方法
#pragma motion移動的類型 UIEvent事件
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    
    //如果是搖手機類型的事件
    if(motion==UIEventSubtypeMotionShake){
NSLog(@"搖動了手機");
//創建並初始化對話框 UIAlertView *show=[[UIAlertView alloc] initWithTitle:@"ocq ios 學習" message:@"恭喜,您查找到了好友" delegate:nil cancelButtonTitle:@"添加為好友" otherButtonTitles: nil]; //顯示對話框 [show show]; // [show release]; 
}
}
@end

 

 

 




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM