Shake a shake function presumably everyone has used, the spring festival time to rob Red envelopes are not less shake it, then use swift language how to achieve such cool features. Shaking belongs to an iOS built-in recognizable action in the Viewcontroller 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 corresponding method, will be described later.
The second sentence is the current page as the first responders, also said we have no matter what 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.) It worked. ", 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 inferred at the end of motion, assuming that motion is shaking, then a warning box pops up. Tip "Congratulations. It worked!
", let's use one of the apps I've been working on recently to test this. This 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. To achieve richer functionality.
Finally, say a little more. Look at the information before the Internet that you need to add methods, because most of the view does not support FirstResponder:
Override Func Canbecomefirstresponder (), Bool { return True }
Maybe this is the version number. I'm using the official version of xcode6.2. There is no need to add this method to the test.
Swift UI special training 39 shake-and-shake function with Swift