1.当设备摇动时,系统会算出加速计的值,并告知是否发生了摇动手势。系统只会运动开始和结束时通知你,并不会在运动发生的整个过程中始终向你报告每一次运动。例如,你快速摇动设备三次,那只会收到一个摇动事件。
2,想要实现摇动手势,首先需要使视图控制器成为第一响应者,注意不是单独的控件。成为第一响应者最恰当的时机是在视图出现的时候,而在视图消失的时候释放第一响应者。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
-(
BOOL
)canBecomeFirstResponder
{
return
YES
;
}
-(
void
)viewDidAppear:(
BOOL
)animated
{
[
super
viewDidAppear:animated];
[
self
becomeFirstResponder];
}
-(
void
)viewWillDisappear:(
BOOL
)animated
{
[
self
resignFirstResponder];
[
super
viewWillDisappear:animated];
}
|
现在,视图控制器准备处理运动事件,其中有三个方法,motionBegan,motionEnded和motionCancelled,这些与触摸方法有着相似的工作原理,但没有移动方法。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
- (
void
)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
if
(event.type == UIEventSubtypeMotionShake)
{
NSLog
(@
"Shake Began"
);
}
}
-(
void
)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
if
(event.type == UIEventSubtypeMotionShake)
{
NSLog
(@
"Shake End"
);
}
}
-(
void
)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
if
(event.type == UIEventSubtypeMotionShake)
{
NSLog
(@
"Shake Cancelled"
);
}
}
|