裝置搖動偵測

1 篇文章 / 0 new
author
裝置搖動偵測
Swift 已封裝, 只需在程式中加入下程式碼(但如需自訂搖動強度則需另外處理)
override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated);
    self.becomeFirstResponder();//沒呼叫也行,用途?
}
override var canBecomeFirstResponder: Bool { return true; }
override func motionBegan(_ motion: UIEventSubtype, with event: UIEvent?) {
        if event?.type == UIEventType.motion && event?.subtype == UIEventSubtype.motionShake {
            print("shakeBegan");
        }
}
override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {
        if event?.type == UIEventType.motion && event?.subtype == UIEventSubtype.motionShake {
            print("shakeEnded");
        }
}
override func motionCancelled(_ motion: UIEventSubtype, with event: UIEvent?) {
        if event?.type == UIEventType.motion && event?.subtype == UIEventSubtype.motionShake {
            print("shakeCancelled");
        }
}
Free Web Hosting