iOS摇一摇功能实现

2016-03-10  本文已影响0人  若怀念

<h6>
看到微信的摇一摇功能是不是感觉很神奇呢?
其实在iOS里想要实现摇一摇功能很简单,方法如下:
</h6>

<li>先在targets -> Build Phases -> Link Binary With Libraries里面添加AudioToolbox.framework;

<li>然后在想要添加摇一摇功能的ViewController里导入:

#import <AudioToolbox/AudioToolbox.h>

<li>接着实现开始、结束、取消摇动的代理方法:

//开始摇动代理方法
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event{
    NSLog(@"开始摇动");
}
//结束摇动代理方法
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event{
    NSLog(@"结束摇动");
    
    //振动效果
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    
    //如果有摇动动作,就做相应操作
    if (event.subtype == UIEventSubtypeMotionShake) {
        NSArray *colorList = @[[UIColor orangeColor],[UIColor brownColor],[UIColor yellowColor],[UIColor redColor],[UIColor blueColor]];
        int rand = arc4random()%5;
        //这里我是让每次摇动随机切换一次self.view的背景颜色
        self.view.backgroundColor = colorList[rand];
    }
}
//取消摇动代理方法
- (void)motionCancelled:(UIEventSubtype)motion withEvent:(nullable UIEvent *)event{
    NSLog(@"取消摇动");
}

在对应的代理方法里写相应的事件就能实现摇一摇功能了。

上一篇 下一篇

猜你喜欢

热点阅读