1. 程式人生 > >ios 中響應震動的幾種方法

ios 中響應震動的幾種方法

  最近在做微信的搖一搖功能,也算是很小的知識點,整理下,免得忘了:

方法有三:

一.繼承自UIWindow(已測試)

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

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    if (motion == UIEventSubtypeMotionShake )
    {
        // User was shaking the device. Post a notification named "shake".
        [[NSNotificationCenter defaultCenter] postNotificationName:@"shake" object:self];//訊息註冊
    }
}

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

實現程式碼後,將window 設為UIResponse

二.(未測試)

首先在App's Delegate中設定applicationSupportsShakeToEdit屬性:

- (void)applicationDidFinishLaunching:(UIApplication *)application {

        application.applicationSupportsShakeToEdit = YES;


}

然後在你的View控制器中新增/過載canBecomeFirstResponder, viewDidAppear:以及viewWillDisappear:

-(BOOL)canBecomeFirstResponder {
    return YES;
}

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

- (void)viewWillDisappear:(BOOL)animated {
    [self resignFirstResponder];
    [super viewWillDisappear:animated];
}

最後在你的view控制器中新增motionEnded:

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    if (motion == UIEventSubtypeMotionShake)
    {
        // your code
    }
}

三。直接在所在view中新增(未測試)

同時讓他成為第一相應者:

- (void)viewDidLoad

{

    [superviewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

    [[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

    }

}