Spe*_*y99 56
Swift3 ios10:
override func viewDidLoad() {
super.viewDidLoad()
self.becomeFirstResponder() // To get shake gesture
}
// We are willing to become first responder to get shake motion
override var canBecomeFirstResponder: Bool {
get {
return true
}
}
// Enable detection of shake motion
override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {
if motion == .motionShake {
print("Why are you shaking me?")
}
}
Run Code Online (Sandbox Code Playgroud)
Rya*_*nes 16
超级易于实施:
1)让iOS知道哪个视图控制器是响应者链中的第一个:
override func viewDidLoad() {
super.viewDidLoad()
self.becomeFirstResponder()
}
override func canBecomeFirstResponder() -> Bool {
return true
}
Run Code Online (Sandbox Code Playgroud)
2)以某种方式处理事件:
override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent?) {
if(event.subtype == UIEventSubtype.MotionShake) {
print("You shook me, now what")
}
}
Run Code Online (Sandbox Code Playgroud)
bso*_*sod 13
斯威夫特 5
iOS 10+
UIApplication、UIViewController、UIView、 和UIWindow都是UIResponder默认对象,这意味着它们都可以处理运动事件,例如摇动,无需任何特殊配置。因此,只需覆盖适当的运动方法:
class YourViewController: UIViewController {
override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
if motion == .motionShake {
print("device did shake")
}
}
}
Run Code Online (Sandbox Code Playgroud)
此外,您可以覆盖motionBegan(_:with:)和motionCancelled(_:with:)。与覆盖某些触摸事件不同,不需要调用 super.
小智 11
这已针对 IOS 12 进行了更新 - 请参阅Apple Docs 您不再需要添加 becomeFirstResponder() 方法。
您只需要在代码中添加motionEnded 函数即可。
override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?)
{
// code here
}
Run Code Online (Sandbox Code Playgroud)
迅捷5
只需将以下方法添加到ViewController并执行代码
override func becomeFirstResponder() -> Bool {
return true
}
override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?){
if motion == .motionShake {
print("Shake Gesture Detected")
//show some alert here
}
}
Run Code Online (Sandbox Code Playgroud)