swift UI專項訓練39 用Swift實現搖一搖功能

來源:互聯網
上載者:User

標籤:toe   tracking   on()   cell   使用   mod   code   網上   csdn   

   的搖一搖功能想必大家都用過,過春節的時候搶紅包也沒少搖吧,那麼用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: "取消", style: .Cancel, handler: nil)            alertController1.addAction(cancelAction)              self.presentViewController(alertController1, animated: true, completion: nil)        }    }

這種方法是在motion結束的時候推斷,假設剛才的motion是搖動的話,那麼彈出一個警告框。提示“恭喜你。成功了!

”,以下我們用我近期在做的一個APP來測試下。這是搖動前的畫面:


然後我們搖動手機,看看效果:



你能夠在這三個方法中增加自己須要的代碼。實現更豐富的功能。

最後再說一點。看網上之前的資料說須要添加方法,由於大部分view不支援firstresponder:

override func canBecomeFirstResponder() -> Bool {        return true    }
可能這是曾經的版本號碼了。我用的是xcode6.2正式版。親測是不須要加這種方法的。

swift UI專項訓練39 用Swift實現搖一搖功能

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.