1. 程式人生 > >搖一搖功能的實現

搖一搖功能的實現

實現搖一搖功能須在檢視控制器中進行編碼。
首先將當前檢視控制器設定為第一響應者;其次實現搖一搖的三個協議方法。
示例如下:

[UIApplication sharedApplication].applicationSupportsShakeToEdit = YES;
[self becomeFirstResponder];
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    if (motion == UIEventSubtypeMotionShake)
    {
        [self.message appendString:@"開始搖一搖功能\n"];
        
        self.label.text = self.message;
    }
}
- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    [self.message appendString:@"結束搖一搖功能\n"];
    
    self.label.text = self.message;
}
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    //搖動結束
    if (event.subtype == UIEventSubtypeMotionShake)
    {
        [self.message appendString:@"取消搖一搖功能\n"];
        
        self.label.text = self.message;
        // 振動效果 需要#import <AudioToolbox/AudioToolbox.h>
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    }
}