2012-04-14 9 views
21

I añade el siguiente código a mi appDelegate.miOS: ¿Cómo detectar el movimiento Shake?

- (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 
{ 
} 

- (void)shakeSuccess 
{ 
    // do something... 
} 

y luego añade:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{ 
    // Override point for customization after application launch. 
    // INIT THE BACKGROUND PATH STRING 

    [self refreshFields]; 
    [self.window addSubview:navController.view]; 
    [self.window makeKeyAndVisible]; 
    ***[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(shakeSuccess) name:@"shake" object:nil];*** 

    return YES; 
} 

Cuando empiezo mi aplicación en mi iPhone, el método llamado "shakeSuccess" no llama . ¿Qué debo hacer para implementar esta función en mi aplicación? alguna idea?

Respuesta

59

Esto podría ayudarle ...
https://stackoverflow.com/a/2405692/796103

dice que se debe configurar el UIApplication 's applicationSupportsShakeToEdit a YES. y anula 3 métodos en su VC:

-(BOOL)canBecomeFirstResponder { 
    return YES; 
} 

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

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

El resto de su código está bien. (El -motionEnded:withEvent:)

+0

¡Impresionante! ¡Funciona genial! muchas gracias. – Samblg

+20

jajaja y él nunca lo hizo. –

+0

"El resto" es el punto. – Itachi

26

Se podría hacer algo como esto ...

En primer lugar ...

Establecer la propiedad en applicationSupportsShakeToEdit Delegado de la App:

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

    application.applicationSupportsShakeToEdit = YES; 

    [window addSubview:viewController.view]; 
    [window makeKeyAndVisible]; 
} 

En segundo lugar ..

Agregar/Anular canBecomeFirstResponder, view DidAppear: y viewWillDisappear: métodos en el controlador de vista:

-(BOOL)canBecomeFirstResponder { 
    return YES; 
} 

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

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

En tercer lugar ...

Añadir el método motionEnded a su controlador de vista:

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

que debería funcionar si el primera respuesta no y esto solo se escribe rápidamente no probado :)

13

Si quieres ser capaz de d etecte el movimiento de sacudida en la aplicación, la mejor manera es anular la clase de su aplicación con una clase personalizada.

y luego implementar esto en su clase de aplicaciones personalizadas

@implementation PSApplication 

- (void)sendEvent:(UIEvent *)event 
{ 
    if (event.type == UIEventTypeMotion && event.subtype == UIEventSubtypeMotionShake) { 
     [[NSNotificationCenter defaultCenter] postNotificationName:@"shakeNotification" object:nil]; 
    } 

    [super sendEvent:event]; 
} 

@end 
+3

Esta es la mejor respuesta para aquellos que buscan un código global de detección de sacudidas dentro de la aplicación, no vinculado al controlador de vista única. – RaffAl

+0

Para anular la aplicación UIA en su main.m ponga esto: 'return UIApplicationMain (argc, argv, @" PSApplication ", NSStringFromClass ([AppDelegate class]));' –

+0

¿Por qué no la subclase '- (void) motionEnded :(UIEventSubtype) motion withEvent: (UIEvent *) event' directamente? – JakubKnejzlik

3

extendí clase UIApplication y referencia de clase añadido a principal: MyApplication.h

@interface MyApplication : UIApplication 

@end 

MyApplication.m

@implementation MyApplication 

- (void) sendEvent:(UIEvent *)event 
{ 
    if(event && (event.subtype==UIEventSubtypeMotionShake)) 
    { 
     AppDelegate *objAppDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate; 

     [objAppDelegate doWhatEver]; 
     [super sendEvent:event]; 
    } 
    else 
    { 
     [super sendEvent:event]; 
    } 
} 

@end 

Y el último paso en main.m

int main(int argc, char *argv[]) 
{ 
return UIApplicationMain(argc, argv, NSStringFromClass([MyApplication class]), NSStringFromClass([AppDelegate class])); 
} 

Esto funciona en todos los casos.

+0

¡Buena solución! Aclamaciones –

Cuestiones relacionadas