首页 > 移动平台 > 详细

iOS开发中实现摇一摇并震动

时间:2015-11-24 12:43:16      阅读:221      评论:0      收藏:0      [点我收藏+]

 首先导入AudioToolbox.framework :project ->TARGETS ->General ->Linked Frameworks and Libraries

注释写的比较清晰,直接上代码了

1 #import <AudioToolbox/AudioToolbox.h> 

label是从sb中随便拖过来方便摇后回调

@property (strong, nonatomic) IBOutlet UILabel *label;
- (void)viewDidLoad {
    [super viewDidLoad];
    //  支持摇一摇  此处应该写在AppDelegate中,为粘贴代码方便写在这里
    [[UIApplication sharedApplication] setApplicationSupportsShakeToEdit:YES];
    //  让此控制器成为第一响应者
    [self becomeFirstResponder];
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self resignFirstResponder];
}

重写下面方法即可摇动回调

//  开始摇动
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event {
    NSLog(@"开始摇动");
    [self animation];
}


- (void)animation {
    CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"position"];
    anim.fromValue = [NSValue valueWithCGPoint:CGPointMake(100, 50)];
    anim.toValue = [NSValue valueWithCGPoint:CGPointMake(100, 500)];
    
    anim.removedOnCompletion = NO;
    anim.duration = 1.0f;
    anim.fillMode = kCAFillModeForwards;
    anim.delegate = self;
    //  随便拖过来的一个label测试效果
    [self.label.layer addAnimation:anim forKey:nil];
}

//  结束摇动
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
    if (event.type == UIEventSubtypeMotionShake ) {
        NSLog(@"摇动结束");
        [self shakeshake];
    }
}
//  摇动结束后执行震动
- (void)shakeshake {
  // 震动
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}

完事,so easy

 

iOS开发中实现摇一摇并震动

原文:http://www.cnblogs.com/chenshuai1012/p/4991122.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!