#import <AudioToolbox/AudioToolbox.h> 必须要加。
// yqs
//
// Created by 陈凯 on 15/6/24.
// Copyright (c) 2015年 leTian. All rights reserved.
//
#import "ViewController.h"
#import <AudioToolbox/AudioToolbox.h>
@interface ViewController ()
@property UIView *yqsview;
@property UIButton *btn;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
_yqsview = [[UIView alloc]init];
_yqsview.frame = CGRectMake(100, 20, 200, 200);
[self.view addSubview:_yqsview];
UIImageView *img = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 200, 200)];
img.image = [UIImage imageNamed:@"1"];
[_yqsview addSubview:img];
//点击摇动 与 手机摇一摇 实现相同效果
_btn = [[UIButton alloc]initWithFrame:CGRectMake(160, 300, 40,20)];
[_btn setTitle:@"摇动" forState:UIControlStateNormal];
[_btn setTitleColor: [UIColor redColor] forState:UIControlStateNormal];
_btn.backgroundColor = [UIColor lightGrayColor];
[self.view addSubview:_btn];
[_btn addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
[[UIApplication sharedApplication] setApplicationSupportsShakeToEdit:YES];//配置支持摇动
[self becomeFirstResponder];
// Do any additional setup after loading the view, typically from a nib.
}
- (void) motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
//检测到摇动
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);//震动
[self shakeView:_yqsview];
}
- (void) motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
//摇动取消
}
- (void) motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
//摇动结束
if (event.subtype == UIEventSubtypeMotionShake) {
//something happens
}
}
- (IBAction)click:(id)sender {
[self shakeView:_yqsview];
}
//抖动实现
- (void)shakeView:(UIView*)viewToShake
{
CGFloat t = 9.0;
CGAffineTransform translateRight = CGAffineTransformTranslate(CGAffineTransformIdentity, t,0.0);
CGAffineTransform translateLeft = CGAffineTransformTranslate(CGAffineTransformIdentity,-t,0.0);
viewToShake.transform = translateLeft;
[UIView animateWithDuration:0.09 delay:0.0 options:UIViewAnimationOptionAutoreverse|UIViewAnimationOptionRepeat animations:^{
[UIView setAnimationRepeatCount:5.0];
viewToShake.transform = translateRight;
} completion:^(BOOL finished){
if(finished){
[UIView animateWithDuration:0.09 delay:0.0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
viewToShake.transform = CGAffineTransformIdentity;
} completion:NULL];
}
}];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end