如何使用 Swift 检测震动手势?


为了检测 iOS UIKit 中的震动手势,提供了三种不同的方法,我们一一来看一下。

方法 1 − 当震动手势开始时。

override func motionBegan(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
// code you want to implement
}

方法 2 − 当震动手势结束时。

override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
// Code you want to implement.
}

方法 3 − 当震动手势取消时。

override func motionCancelled(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
// code you want to implement.
}

现在,让我们在 motionBegan 方法中添加一些代码,

override func motionBegan(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
   print(motion)
   if motion == .motionShake {
      print("shake was detected")
   }
}

还在 viewDidLoad() 方法中添加 “self.becomeFirstResponder()”。当我们在模拟器上运行 obve 代码并使用调试来生成震动手势时,下面就是生成的结果。我们可以根据自己的使用情况修改上面的代码,并且在我们应用程序中执行不同的操作。

更新于:29-6 月-2020

918 次浏览

开启您的职业生涯

完成课程获得认证

立即开始学习
广告
© . All rights reserved.