The method of realizing gesture recognition in Swift program _swift

Source: Internet
Author: User

In this iOS application development tutorial, we intend to implement gesture recognition. As you know, iOS supports a large number of gesture operations that provide good application control and an excellent user experience.
let's get started!

You first need to create a new single View application in Xcode:

Then click Next and the pop-up window asks you to fill out the project settings. After you fill in the name of the project in the first column ("Product name"), click Next.

Make sure that the language chooses "Swift".

Design interface

Click on the "Main.storyboard" file and drag out 6 uiviews into the view. Arrange the view as shown. When you arrange Uiviews, add a uilabel below each view and set the text value according to the diagram.

Let's start writing code.

It's time to edit the implementation file (in our case "Viewcontroller.swift").

To declare some of the variables we'll be using, add the following code to the "Class Viewcontroller:uiviewcontroller" block.


Copy Code code as follows:
Class Viewcontroller:uiviewcontroller {
@IBOutlet var Tapview:uiview
@IBOutlet var Swipeview:uiview
@IBOutlet var Longpressview:uiview
@IBOutlet var Pinchview:uiview
@IBOutlet var Rotateview:uiview
@IBOutlet var Panview:uiview
var lastrotation = CGFloat ()
Let Taprec = UITapGestureRecognizer ()
Let Pinchrec = Uipinchgesturerecognizer ()
Let Swiperec = Uiswipegesturerecognizer ()
Let Longpressrec = Uilongpressgesturerecognizer ()
Let Rotaterec = Uirotationgesturerecognizer ()
Let Panrec = Uipangesturerecognizer ()
}

In line 2–7, we declare the uiviews that have been arranged in the previous interface.

On line 8th, we declare the variable (lastrotation) to be used to implement the rotation gesture.

In line 9–14, we declare a gesture recognition object for each view.

Note: In swift, we declare a constant with the Let keyword, which means its value cannot be changed while the program is running. The keyword var declares a generic variable.


After declaring the main variables required by the application, add the following code in the Viewdidload method.


Copy Code code as follows:
Override Func Viewdidload () {
Super.viewdidload ()
Taprec.addtarget (Self, Action: "Tappedview")
Pinchrec.addtarget (Self, Action: "Pinchedview:")
Swiperec.addtarget (Self, Action: "Swipedview")
Longpressrec.addtarget (Self, Action: "Longpressedview")
Rotaterec.addtarget (Self, Action: "Rotatedview:")
Panrec.addtarget (Self, Action: "Draggedview:")
Tapview.addgesturerecognizer (TAPREC)
Swipeview.addgesturerecognizer (SWIPEREC)
Pinchview.addgesturerecognizer (PINCHREC)
Longpressview.addgesturerecognizer (LONGPRESSREC)
Rotateview.addgesturerecognizer (ROTATEREC)
Panview.addgesturerecognizer (PANREC)
Rotateview.userinteractionenabled = True
Rotateview.multipletouchenabled = True
Pinchview.userinteractionenabled = True
Pinchview.multipletouchenabled = True
Tapview.userinteractionenabled = True
Swipeview.userinteractionenabled = True
Longpressview.userinteractionenabled = True
Panview.userinteractionenabled = True
}

Line 3–8, set the target of gesture recognition for each view. The so-called goal is the method to be invoked when the gesture is completed in each view.

第9-14 the line to add gesture recognition to the view.

Line 15–22, set the Userinteractionenabled property of each view to ture, and the view that has the gesture that requires multi-touch (Rotateview and Pinchview) to be multipletouchenabled property is set to true.

Now, we write the method to be invoked by each gesture recognizer (the target method set by the 3–8 line).

Add the following code:


Copy Code code as follows:
Func Tappedview () {
Let Tapalert = Uialertcontroller (title: "Tapped", message: "You just tapped the tap view", Preferredstyle:uialertcontroll Erstyle.alert)
Tapalert.addaction (title: "OK", Style: Uialertaction. Destructive, Handler:nil))
Self.presentviewcontroller (Tapalert, Animated:true, Completion:nil)
}

Func Swipedview () {
Let Tapalert = Uialertcontroller (title: "Swiped", Message: "You just swiped the swipe view", Preferredstyle:uialertcontro Llerstyle.alert)
Tapalert.addaction (title: "OK", Style: Uialertaction. Destructive, Handler:nil))
Self.presentviewcontroller (Tapalert, Animated:true, Completion:nil)
}

Func Longpressedview () {
Let Tapalert = Uialertcontroller (title: ' Long pressed ', message: ' You just long pressed the long press view ', Preferredsty Le:UIAlertControllerStyle.Alert)
Tapalert.addaction (title: "OK", Style: Uialertaction. Destructive, Handler:nil))
Self.presentviewcontroller (Tapalert, Animated:true, Completion:nil)
}

These three methods do the same thing well. Each method pops up a dialog box each time the gesture is completed in the appropriate view.


So the Tappedview () method pops up a dialog box when the user slides the view, and the Swipedview () method pops up a dialog while the user touches the swipe view, while the Longpressedview () method is the user's long press Pop-up dialog box when view.

The code for the other two gestures (rotate and pinch) is a little more complicated.

Add the following code for the rotation gesture:


Copy Code code as follows:
Func Rotatedview (Sender:uirotationgesturerecognizer) {
var lastrotation = CGFloat ()
Self.view.bringSubviewToFront (Rotateview)
if (sender.state = = uigesturerecognizerstate.ended) {
lastrotation = 0.0;
}
rotation = 0.0-(lastrotation-sender.rotation)
var point = Rotaterec.locationinview (Rotateview)
var Currenttrans = Sender.view.transform
var Newtrans = cgaffinetransformrotate (Currenttrans, rotation)
Sender.view.transform = Newtrans
Lastrotation = Sender.rotation
}

This method contains Sender:uirotationgesturerecognizer parameters. The sender parameter (uirotationgesturerecognizer type) contains the value of the gesture recognizer called by this method (which is rotaterec in this case).

Line 2nd declares the lastrotation.

Line 3rd Let's put the Rotateview in the front.


Next, in the IF statement, we check if the gesture is complete, and if not, we rotate the view.

8–10 line, we calculate the rotation of the rotate view, and in line 10th we set the degree of rotation of the rotate view.

On line we set the lastrotation as the current rotation of the rotation gesture recognizer.

Now we add the code for the pinch gesture:

Copy Code code as follows:
Func Pinchedview (Sender:uipinchgesturerecognizer) {
Self.view.bringSubviewToFront (Pinchview)
Sender.view.transform = Cgaffinetransformscale (Sender.view.transform, Sender.scale, Sender.scale)
Sender.scale = 1.0
}

In line 1th of the previous method, we put the pinch view to the top. Then set the transform for each pinch view and set the Pinchrec scale to 1.

Then it implements the pan (drag) gesture. Add the following code:


Copy Code code as follows:
Func Draggedview (Sender:uipangesturerecognizer) {
Self.view.bringSubviewToFront (Sender.view)
var translation = Sender.translationinview (Self.view)
Sender.view.center = Cgpointmake (sender.view.center.x + translation.x, Sender.view.center.y + translation.y)
Sender.settranslation (Cgpointzero, InView:self.view)
}

Line 2nd, we put the drag view to the top (same as the previous method).

Then we declare the variable translation and assign the value to it using the value of Sender.translationinview (Self.view). When you are done, set the center property of the Sender.view object (PANREC) to the computed new Center (through Cgpointmake (sender.view.center.x + translation.x, Sender.view.center.y + TRANSLATION.Y) and set the translation to Sender (Panrec).

Now, the code section is complete!

Back to the interface design.

Now we go back to the "Main.storyboard" file. Select the view controller and connect each uiview of the declaration to the appropriate view, as shown in the following illustration.

Completed

Now you can run the application on the emulator or your device and test the gesture.
PostScript

I hope this tutorial will be of some help to you. You can download the full source code

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.