iOS摇一摇的使用

一、实现系统自带的motionBegan方法

1
2
3
4
5
6
/// 开始
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event NS_AVAILABLE_IOS(3_0);
/// 结束
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event NS_AVAILABLE_IOS(3_0);
/// 取消
- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event NS_AVAILABLE_IOS(3_0);

假如程序不响应此方法,再实现以下方法:

1
2
3
4
- (BOOL)canBecomeFirstResponder
{
    return YES;
}


二、motionBegan+通知的方法(建议)

1.在Appdelegate里写motionBegan方法

1
2
3
4
-(void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"SAMotionBegan" object:@(motion)];
}

2.在需要接收通知的页面添加通知

1
2
3
4
5
6
7
8
9
10
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [SANotice addObserver:self selector:@selector(shake) name:@"SAMotionBegan" object:nil];
}
 
- (void)shake
{
    SALog(@"摇一摇开始...");
}

Leave a Reply