微信的摇一摇功能想必大家都用过,过年的时候抢红包也没少摇吧,那么用swift语言如何实现这么酷炫的功能呢。摇动属于IOS内置可识别的一种动作,在你需要实现摇动功能的viewcontroller中,在viewDidLoad方法中加入以下代码:
UIApplication.sharedApplication().applicationSupportsShakeToEdit = true
self.becomeFirstResponder()
第一句是要求当前页面支持对摇动事件可编辑的支持,设置为true后我们可以实现相应的方法,稍后会介绍。
第二句是把当前页面作为第一反应者,也就说我们有任何操作结果都会反映到当前页面中。
现在我们可以使用与摇动相关的方法了,主要有三个:motionBegin、motionEnded、motionCancelled。
分别捕获摇动开始、摇动结束和摇动取消三个动作。我们选用motionEnded来举例:
override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent) {
if motion == UIEventSubtype.MotionShake
{
var alertController1 = UIAlertController(title: "恭喜你,成功了!", message: nil, preferredStyle: .Alert)
var cancelAction = UIAlertAction(title: "取消",