【问题标题】:Can't get shake events on iPhone无法在 iPhone 上获取震动事件
【发布时间】:2011-04-03 22:03:33
【问题描述】:

我无法在 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 和一个对象,我的控制器。

我的想法已经不多了,希望有人能帮帮我。 :)

【问题讨论】:

标签: iphone cocoa-touch shake motion-detection


【解决方案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];
}

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • event.subtype 和 motion 在我的测试中是一样的。
    【解决方案3】:

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

    -(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
        if ( event.subtype == UIEventSubtypeMotionShake ) {
            // Put in code here to handle shake
        }
    }
    

    【讨论】:

    • @MegaEduX:您尝试了我的原始代码还是修改后的答案?
    • 我也试过 event.subtype 。 Apple 的示例检查运动,这就是我使用它的原因。反正又试了一次,没用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多