iOS摇一摇功能实现

<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(@"取消摇动");
}

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容