iOS 微信摇一摇的实现

微信的摇一摇是怎么实现的,在 UIResponder中存在这么一套方法

- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)even __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_3_0);

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_3_0);

- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_3_0);

//这就是执行摇一摇的方法。那么怎么用这些方法呢?

//很简单,你只需要让这个Controller本身支持摇动

//同时让他成为第一相应者:

- (void)viewDidLoad

{

[superviewDidLoad];

[[UIApplicationsharedApplication] setApplicationSupportsShakeToEdit:YES];

[selfbecomeFirstResponder];

}

//然后去实现那几个方法就可以了

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

{

//检测到摇动

}



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

{

//摇动取消

}



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

{

//摇动结束

    if (event.subtype == UIEventSubtypeMotionShake) {

    //something happens

}

}

swift中对应的代码

 application.applicationSupportsShakeToEdit = true
 self.becomeFirstResponder()

对应的方法

 override func motionBegan(motion: UIEventSubtype, withEvent event: UIEvent?) {
    super.motionBegan(motion, withEvent: event)
    UIApplication.sharedApplication().keyWindow?.rootViewController = UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController()
}

override func motionCancelled(motion: UIEventSubtype, withEvent event: UIEvent?) {
    super.motionCancelled(motion, withEvent: event)
}

override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent?) {
    super.motionEnded(motion, withEvent: event)
}

注意,测试用真机哦,别用电脑摇来摇去-。-

你可能感兴趣的:(iOS 微信摇一摇的实现)