iphone ios UIAccelerometer教程/用法

来源:互联网 发布:新理念外语网络教学 编辑:程序博客网 时间:2024/05/21 06:51

希望各位能支持一下我们的网站:http://t.cn/zOdAUxJ  提提意见


转载一篇老外的文章

If you like this tutorial, feel free to send me a donation at baseballer1149@aol.com via paypal.
First off, the UIAccelerometer is something that a lot of apps use. It's that thing that automatically detects when the user has moved his/her iphone. It measures on 3 axis, and they are the following.

X: When the user moves iphone left/right
Y: When the user moves iphone forward/backward
Z: When the user moves the iphone up/down

Now, to use this in an application.
Go ahead and open up a new View-based application.
Lets name is accel.
Now, open up accelViewController.h and add an IBOutlet for a UILabel

Code:
// code@interface accelViewController : UIViewController < UIAccelerometerDelegate >{IBOutlet UILabel *label;}@property (nonatomic, retain) IBOutlet UIlabel *label;// end of code
quickly open up the *.m file and put in the following (underneath @implementation)

Code:
@synthesize label;
this will create getter and setter methods for changing values about our label

now, open up the .nib file for this view.
Drag on a UILabel, and in connections inspector drag from "New Referencing Outlet" to files owner, and select the label outlet.

Now, head back to the *.m file

uncomment the viewDidLoad method (towards the bottom of the file)
And inside of the viewDidLoad method, put the following:

Code:
[label setText:@"fixed"]UIAccelerometer *accel = [UIAccelerometer sharedAccelerometer];accel.delegate = self;accel.updateInterval = 1.0f/60.0f;
Ok, now an explanation:

Code:
[label setText:@"fixed"];
sets our label to "fixed"

Code:
UIAccelerometer *accel = [UIAccelerometer sharedAccelerometer];
gets a reference to the devices shared accelerometer.

Code:
accel.delegate = self;accel.updateInterval = 1.0f/60.0f;
sets the delegate, and how many times it will check per second.
Increasing that value 1.0f/60.0f may put strain on the battery

Now, all thats left is to implement the accelerometer:didAccelerate method

somewhere in the file, add this method:

Code:
- (void)accelerometer:(UIAccelerometer *)acel didAccelerate:(UIAcceleration *)aceler {if (fabsf(aceler.x) > 1.5 || fabsf(aceler.y) > 1.5 || fabsf(aceler.z) > 1.5){if ([label.text isEqualToString:@"Broken"] == YES){[label setText:@"Fixed"];}else{[label setText:@"Broken"];}             }
now, you're good. One thing left to explain. UIAcceleration has 3 values to it, X, Y, and Z. In order to assure the gesture wasn't by accident, we test to see if each value is above 1.5. You can use this in numerous ways, you just have to think of creative things. Instead of buttons, sometimes think of all the other things the iphone can do, and use those (accelerometer, microphone, etc.)

Have fun and post comments if you need help

Oh, and don't forget to build-run the app!