iPhone: modifying view when user shakes

女生的网名这么多〃 提交于 2019-12-02 10:06:41

In order for you to check if the phone's been shaken, your class will have to use the UIAccelerometerDelegate protocol.

For example:

@interface myTableViewClass : UITableView <UIAccelerometerDelegate>

Then, you need to be able to tell when the phone's been shaken (I use this in my viewDidLoad):

[[UIAccelerometer sharedAccelerometer] setDelegate:self];
[[UIAccelerometer sharedAccelerometer] setUpdateInterval:0.1];

Once the user shakes the phone, you can do your magic in this method:

- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration 
{   
    if(fabsf(acceleration.x) > 2.2 || fabsf(acceleration.y) > 2.2 || fabsf(acceleration.z) > 2.2){
        //The user has shaken the iPhone
    }
}

You can obviously change the interval to check more often and change the parameters on the accelerometer:didAccelerate method to suit your needs.

Check these methods/APIs:

- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event

- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event

These are event handlers provided for motion recognition. Go through the document before using these.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!