Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
610 views
in Technique[技术] by (71.8m points)

objective c - How to detect shake motion in iPhone

On the shake of the iPhone device i want some function to be called, i dont know how to recognize shake so i tried some link and tried this code

- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    if(event.type == UIEventSubtypeMotionShake)
    {
        NSLog(@"called");
        [self.view setBackgroundColor:[UIColor greenColor]];
    }
}

- (BOOL)canBecomeFirstResponder
{ 
return YES; 
}

But alas no luck so can you please let me know how i can do the same

Thanks and Regards

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As per the above comments discussed i am answering my question so that others can read the solution that i have got

In the UIResponder class documentation it is said that the motion events will respond to the first responder only so what i did was add just a small function and that did the trick for me, so here's my solution

- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    if(event.type == UIEventSubtypeMotionShake)
    {
        NSLog(@"called");
        [self.view setBackgroundColor:[UIColor greenColor]];
    }
}

- (BOOL)canBecomeFirstResponder
{ 
return YES; 
}

Now still i was not able to detect any shake motion so all i had to do was to make my viewcontroller the first responder and for that here's the code that i used

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

and i was done

This was the solution that i came up with

Thanks and Regards


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...