Shake a shake function presumably everyone has used, the new Year's time to rob red envelopes did not less shake it, then the swift language how to achieve such cool features. Shake belongs to an iOS built-in recognizable action, in the viewcontroller that you need to implement the Shake function, add the following code to the Viewdidload method:
Uiapplication.sharedapplication (). Applicationsupportsshaketoedit = True self.becomefirstresponder ()
The first sentence is to require the current page support for the shaking event editable support, set to true after we can implement the appropriate method, will be described later.
The second sentence is the current page as the first responders, also said that we have any operation results will be reflected in the current page.
Now we can use the method related to the shaking, there are three main: Motionbegin, motionended, motioncancelled.
Capture shake start, shake end, and shake to cancel three actions respectively. We use motionended to illustrate:
Override Func motionended (Motion:uieventsubtype, withevent event:uievent) { if motion = = Uieventsubtype.motionshake { var alertController1 = Uialertcontroller (title: "Congratulations, you've succeeded!") ", Message:nil, Preferredstyle:. Alert) var cancelaction = uialertaction (title: "Cancel", Style:.) Cancel, Handler:nil) alertcontroller1.addaction (cancelaction) Self.presentviewcontroller ( AlertController1, Animated:true, Completion:nil) } }
This method is judged at the end of motion, and if motion is shaking, a warning box pops up, prompting, "Congratulations! "Now, let's test it with one of the apps I've been working on recently, which is the picture before shaking:
Then we shake the phone and look at the effect:
You can add the code you need in these three ways for richer functionality.
Last but not least, look at the information on the Internet that requires additional methods because most of the view does not support FirstResponder:
Override Func Canbecomefirstresponder (), Bool { return True }
Perhaps this is the previous version, I use the xcode6.2 version, the pro-test is not required to add this method.
Swift UI special training 39 shake-and-shake function with Swift