Swift - 手机摇晃的监测和响应

时间:2023-03-08 17:07:18
摇晃手机也是一种常用的交互手段(比如微信摇一摇功能)。iOS SDK中已经将shake事件方便地融合进去了,就像触发touch事件一样简单,发生摇晃事件后程序会自动执行。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import UIKit
class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
    }
     
    //开始摇晃
    override func motionBegan(motion: UIEventSubtype, withEvent event: UIEvent) {
        println("开始摇晃")
    }
     
    //摇晃结束
    override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent) {
        println("摇晃结束")
    }
     
    //摇晃被意外终止
    override func motionCancelled(motion: UIEventSubtype, withEvent event: UIEvent) {
        println("摇晃被意外终止")
    }
}