0

我无法在 iPhone 上获得震动事件。

我在这里关注了其他问题,但没有结果。我也尝试遵循 Apple 的 GLPaint 示例,但它看起来与我的源代码完全一样,只是略有不同。GLPaint 的源代码 /works/,我的 /doesn't/。

所以,这就是我所拥有的:

控制器.m

- (void)awakeFromNib {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(shakeEnded) name:@"shake" object:nil];
}

ShakingEnabledWindow.m

- (void)shakeEnded {
    NSLog(@"Shaking ended.");
}

- (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];
        NSLog(@"Shaken!");
    }
}

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

我的 XIB 有一个窗口,它是一个 ShakingEnabledWindow 和一个对象,我的控制器。

我的想法在这里用完了,希望有人能帮帮我。:)

4

3 回答 3

1

NSNotificationCenter 的文档说:

addObserver:selector:name:object: notificationSelector选择器,指定接收方发送 notificationObserver 以通知其通知发布的消息。notificationSelector 指定的方法必须有一个且只有一个参数(NSNotification 的一个实例)。

所以你的shakeEnded 方法是错误的,因为它没有参数。它应该看起来:

- (void)shakeEnded:(NSNotification*)notiication {
    NSLog(@"Shaking ended.");
}

- (void)awakeFromNib {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(shakeEnded:) name:@"shake" object:nil];
}
于 2011-04-03T22:09:39.407 回答
1

viewDidAppear中,成为第一响应者:

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

并确保您可以成为第一响应者:

- (BOOL)canBecomeFirstResponder {
    return YES;
}

然后你可以实现运动检测。

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    if (event.subtype == UIEventTypeMotion){
        //there was motion
    }
}
于 2011-04-03T22:44:42.557 回答
0

我认为您错误地检查了运动类型。您需要检查event.subtype而不是motion

-(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
    if ( event.subtype == UIEventSubtypeMotionShake ) {
        // Put in code here to handle shake
    }
}
于 2011-04-03T22:08:35.753 回答