Peter Kazazes
Peter Kazazes

Reputation: 3628

How do I respond to the user shaking an iPhone?

Alright, so to get going with Objective-C (I'm usually just an HTML PhoneGap kinda guy), I made a simple Magic 8 ball app. I've got it right now so that when I touch the screen, the ball "shakes" and takes a random response and puts it in a label. What I want to do is when the iPhone itself is shaked, the text is updated too.

Here's my MainView.m:

#import "MainView.h"

@implementation MainView

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
 if (event.type == UIEventSubtypeMotionShake) {
  int rNumber = rand() % 26;
  switch (rNumber) {
                case 0:
                    shook.text = @"Never";
                    break;
            ....25 more entries.....
                default:
                    break;
           }
    }
 }

 - (IBAction)yesNo {
 [NSThread sleepForTimeInterval:0.75];
 int rNumber = rand() % 26;
 switch (rNumber) {
  case 0:
   result.text = @"Never";
   break;
  ........
  default:
  break;
 }
 }

 @end

and my MainView.h

 #import <UIKit/UIKit.h>
 #import <Foundation/Foundation.h>

 @interface MainView : UIView <UIAccelerometerDelegate> {
     IBOutlet UILabel *result;
  IBOutlet UILabel *shook;
 }

 - (IBAction)yesNo;
 - (void)motionEnded;

 @end     

Obviously there's an error in there, I know that much, but where?!

Upvotes: 0

Views: 292

Answers (1)

Quintin Willison
Quintin Willison

Reputation: 630

It looks like you need to read the documentation in more depth to get to the bottom of this. Specifically the iOS Event Handling Guide.

From that document there are a few things which I would suggest you try:

  1. Override canBecomeFirstResponder: and return YES (as per Listing 4-1).
  2. Override viewDidAppear:animated: to become the first responder (as per Listing 4-1).
  3. Override both motionBegan:withEvent: and motionCancelled:withEvent: as they do this in the example which may be because the framework is testing your view controller class to see if it responds to these selectors (as per Listing 4-2).

Look at the UIResponder Class Reference (from which UIViewController inherits) for more detail on the methods you are overriding.

As someone who came from a Microsoft / VB / .NET and Android / Java background to Cocoa / Objective-C programming I would strongly suggest you invest the time in reading the documentation. Initially the Apple documents seem impenetrable but they're actually pretty good!

I hope that helps.

Upvotes: 1

Related Questions