Swift UI special training 39 use Swift to implement the shake function, uiswift
Everyone must have used the shake function. during the Chinese New Year, it's not enough to shake the red envelope. So how can we use swift to implement such a cool function. Shaking is a built-in recognizable IOS action. Add the following code to the viewcontroller that implements the shaking function in the viewDidLoad method:
UIApplication.sharedApplication().applicationSupportsShakeToEdit = true self.becomeFirstResponder()
The first sentence requires that the current page support editable shaking events. If it is set to true, we can implement the corresponding method. We will introduce it later.
The second sentence is to take the current page as the first responder, that is, any operation results will be reflected in the current page.
Now we can use three methods related to shaking: motionBegin, motionEnded, and motionCancelled.
Capture the start, end, and cancel actions of the shaking. We use motionEnded as an example:
Override func motionEnded (motion: UIEventSubtype, withEvent event: UIEvent) {if motion = UIEventSubtype. MotionShake {var alertController1 = UIAlertController (title: "Congratulations! ", Message: nil, preferredStyle :. alert) var cancelAction = UIAlertAction (title: "canceled", style :. cancel, handler: nil) alertController1.addAction (cancelAction) self. presentViewController (alertController1, animated: true, completion: nil )}}
This method is determined at the end of the motion. If the motion is shaken, a warning box is displayed, prompting "Congratulations, you have succeeded !", Let's test it with an app I recently developed. This is the picture before shaking:
Then let's shake the phone to see the effect:
You can add the required code to these three methods to implement richer functions.
Finally, we need to add methods to read the previous online materials because most views do not support firstresponder:
override func canBecomeFirstResponder() -> Bool { return true }
Maybe this is a previous version. I use the official xcode6.2 version. This method is not required for the test.