四,iOS 界面中的摇一摇功能实现

首先导入头文件

#import <AudioToolbox/AudioToolbox.h> //震动需要的库
#import <CoreMotion/CoreMotion.h> //摇一摇需要的库

  //支持摇一摇并让他成为第一响应事件
    [[UIApplication sharedApplication]setApplicationSupportsShakeToEdit:YES];
    
    [self becomeFirstResponder];

具体的代码如下

@interface MotionShakeViewController ()
@property (nonatomic , strong) UILabel *pedoLab;

@end

@implementation MotionShakeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //支持摇一摇并让他成为第一响应事件
    [[UIApplication sharedApplication]setApplicationSupportsShakeToEdit:YES];
    
    [self becomeFirstResponder];
    
    [self.view addSubview:self.pedoLab];
   
}
- (UILabel *)pedoLab{
    if (!_pedoLab) {
        _pedoLab = [[UILabel alloc]initWithFrame:CGRectMake(20, 220, W -40, 60)];
        _pedoLab.backgroundColor = DB_Blue;
        _pedoLab.textColor  = [UIColor whiteColor];
        _pedoLab.font = Font_CN(15);
        _pedoLab.textAlignment = NSTextAlignmentCenter;
    }
    return _pedoLab;
}
#pragma mark 摇一摇代码实现
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent*)event
{
    //检测到摇动
    NSLog(@"1234567开始摇动");
    self.pedoLab.text = [NSString stringWithFormat:@"%@",@"开始摇动"];

}

- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent*)event
{
    //摇动取消
    self.pedoLab.text = [NSString stringWithFormat:@"%@",@"摇一摇取消"];

}

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent*)event
{
    //摇动结束
    /* 系统的震动不支持ipad touch **/
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    if(event.subtype == UIEventSubtypeMotionShake) {
        
        //somethinghappens
        NSLog(@"123344554566");
        self.pedoLab.text = [NSString stringWithFormat:@"%@",@"摇一摇结束"];
        
    }
    
}
-(BOOL)canBecomeFirstResponder {
    return YES;
}

-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self becomeFirstResponder];
}

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


  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值