iOS中实现摇一摇有两种方式,一种是通过加速器实现,一种是通过系统提供的方法来实现,简单的令人发指.
UIResponder 类中提供了摇一摇开始,取消,结束的方法:
<pre><code>` override func motionBegan(_ motion: UIEventSubtype, with event: UIEvent?) {
}
override func motionCancelled(_ motion: UIEventSubtype, with event: UIEvent?) {
}
override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {
}`</code></pre>
viewDidLoad中可以设置控制器可以执行摇一摇,也可以不设置:
<pre><code>` override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
UIApplication.shared.applicationSupportsShakeToEdit = true
self.becomeFirstResponder()
}`</code></pre>
摇一摇执行的时候可以播放声音,结束的时候可以设置结束的事件,实现代码:
<pre><code>` override func motionBegan(_ motion: UIEventSubtype, with event: UIEvent?) {
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
let path:String? = Bundle.main.path(forResource: "shake", ofType: "mp3")
if path != nil {
var soundID:SystemSoundID?
AudioServicesCreateSystemSoundID(URL.init(fileURLWithPath: path!) as CFURL,&soundID!)
//播放声音
AudioServicesPlaySystemSound(soundID!)
}
print("FlyElephant--motionBegan")
}
override func motionCancelled(_ motion: UIEventSubtype, with event: UIEvent?) {
print("FlyElephant---motionCancelled")
}
override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {
print("FlyElephant--motionEnded")
if event?.subtype == UIEventSubtype.motionShake {
print("FlyElephant--motionEnded")
}
}`</code></pre>