how to detect and program around shakes for the iphone

后端 未结 2 945
盖世英雄少女心
盖世英雄少女心 2020-12-16 04:59

I\'m trying to implement the shake \"tutorial\" on this page, but I think I\'m missing something. I copied his accelerometer function into myAppViewController.m file and pu

2条回答
  •  生来不讨喜
    2020-12-16 05:44

    Here is my answer that works:

    //MainViewController.m

    -(void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event {
    
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(shake) 
                                     name:@"shake" object:nil];
    
        if(event.type == UIEventTypeMotion && event.subtype == UIEventSubtypeMotionShake)
            NSLog(@"motion Began");
    }
    
    -(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(shake)
                                                     name:@"shake"
                                                   object:nil];
        if(event.type == UIEventTypeMotion && event.subtype == UIEventSubtypeMotionShake)
            NSLog(@"motion Ended");
    }
    
    -(void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event {
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(shake) 
                                                     name:@"shake" 
                                                   object:nil];
        if(event.type == UIEventTypeMotion && event.subtype == UIEventSubtypeMotionShake)
            NSLog(@"motion Cancelled");
    }
    
    -(void)viewDidLoad {
        [super viewDidLoad];
    
        [self becomeFirstResponder];
    }
    
    - (void)viewDidUnload {
        // Release any retained subviews of the main view.
        // e.g. self.myOutlet = nil;
        [self resignFirstResponder]; 
    
    }
    

    I tested only with simulator and it returns me:

    2010-06-22 12:40:48.799 Cocktails[14589:207] motion Began
    
    2010-06-22 12:40:48.800 Cocktails[14589:207] motion Ended
    

    I hope this help, because I loose 2 hours of doing this work.

提交回复
热议问题