iOS Tutorials: Introduction to UIGestureRecognizer

UIGestureRecognizer

UIGestureRecognizer tracks the touch behavior on screen interpreted by user such as tap, pinches, rotations, swipes, pans and long presses and act on the recognition based on the action method written. With the introduction of UIGestureRecognizer, it definitely will save you more time from writing additional codes.

There are six types of gesture recognizer:
  1. UITapGestureRecognizer – recognize tap
  2. UIPinchGestureRecognizer – recognize pinch (zoom in/out)
  3. UIRotationGestureRecognizer – recognize rotation
  4. UISwipeGestureRecognizer – recognize swipping
  5. UIPanGestureRecognizer – recognize dragging
  6. UILongPressGestureRecognizer – recognize long tap

UIPanGestureRecognizer

With UIPanGestureRecognizer, you could move an object around the screen. An example shown below shows a chicken being moved around the screen

This could easily be implemented with the following instructions:

  1. Store a chicken image in Assets.xcassets
  2. Drag Image View onto Main.storyboard and notice on the top right screen, name it according what your image name is on the Assets.xcassets and on the inspector panel, tick User Interaction Enabled
  3. Drag Pan Gesture Recognizer onto the image
  4. Write an action and control + drag Pan Gesture Recognizer to View Controller and select the button below Sent Actions. It should look like the image below. 
  5. Write the code in the action method

By calling translation(in:) here, you could detect the movement through the finger. And when the user lift his finger off the object, in order for image to stay at that position, we will have to set the translation at zero or else the object would be thrown off the screen.

@IBAction func panGesture(recognizer : UIPanGestureRecognizer) {
   let trans = recognizer.translation(in: self.view)
   recognizer.view?.center = CGPoint(x:(recognizer.view?.center.x)! + trans.x, y:(recognizer.view?.center.y)! + trans.y)
   recognizer.setTranslation(CGPoint.zero, in: self.view)
}

UITapGestureRecognizer

With UITapGestureRecognizer, you are able to track the touches of the users. There are different state in which you could track the touches:

  • Possible – This is the default state in which the gesture is not yet recognized but is evaluating the touch events.
  • Began – This gesture is recognized as a continuous gesture.
  • Changed – This gesture is recognized as a change to a continuous gesture.
  • Ended – This gesture is recognized as the end of a continuous gesture.
  • Cancelled – This gesture is recognized as the cancellation of a continuous gesture.
  • Failed – This gesture isn’t recognized any multi-touch

We will be implementing .ended in this example as we will only be detecting the by each click. The result should look like the image below.

  1. Drag Tap Gesture Recognizer onto the image and control + drag Tap Gesture Recognizer to View Controller and click on the action. (Make sure you have the IBAction method written)
  2. Write the code
@IBAction func tapGesture(recognizer : UITapGestureRecognizer) {
    if recognizer.state == .ended{
        let alert = UIAlertController(title: "Message", message: "Would you like to eat the chicken?", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Yes", style: .default, handler: nil))
        alert.addAction(UIAlertAction(title: "No", style: .default, handler: nil))
        self.present(alert, animated: true)
    }
}

UIRotationGestureRecognizer

With UIRotationGestureRecognizer, you are able to rotate anything that you would like. For this case, we would rotate the chicken as seen from the example below.

  1. Drag Rotation Gesture Recognizer onto the Image and Control + Drag Rotation Gesture Recognizer to View Controller and select the action(Make sure you write your function).
  2. Write the code

With the code here, we are using several state mentioned earlier such as .began, .changed and .ended. And when it entered each state, it will perform the necessary action.

In order to keep track of the last rotation, last is given the value of 0 as we have not done any rotation. And if we do rotate, we’ll store the value in original. And when we stop rotating, we’ll save recognizer.rotation into last. With this, we could prevent the image from going back to the default rotation. 

@IBAction func rotateGesture(recognizer: UIRotationGestureRecognizer){
    var original = CGFloat()
    var last: CGFloat = 0
        
    if recognizer.state == .began {
        recognizer.rotation = last
        original = recognizer.rotation
     } else if recognizer.state == .changed {
        let new = recognizer.rotation + original
        recognizer.view?.transform = CGAffineTransform(rotationAngle: new)
     } else if recognizer.state == .ended {
        last = recognizer.rotation
     }
}

UIPinchGestureRecognizer

With UIPinchGestureRecognizer, you’ll be able to zoom in/out for an image.

  1. Drag Pinch Gesture Recognizer onto the image and control + drag Pinch Gesture Recognizer to View Controller and click on the action. (Make sure you have the IBAction method written)

2. Write the code

@IBAction func pinchGesture(recognizer: UIPinchGestureRecognizer){
    recognizer.view?.transform = (recognizer.view?.transform)!.scaledBy(x: recognizer.scale, y: recognizer.scale)
    recognizer.scale = 1.0
}

UILongPressGestureRecognizer

With UILongPressGestureRecognizer, you could detect long touch by user and initiate the action that you have set. The following example can be shown below. This is indeed 3 seconds, I cut the length to make the GIF file smaller.

  1. Drag Long Press Gesture Recognizer onto the image and control + drag Long Press Gesture Recognizer to View Controller and click on the action. (Make sure you have the IBAction method written)
  2. Write the code
@IBAction func longPressGesture(recognizer: UILongPressGestureRecognizer){
    recognizer.minimumPressDuration = 3
    let alert = UIAlertController(title: "Long Press Gesture Activated", message: "Minimum Press Duration is 3 second", preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
    self.present(alert, animated: true)
}

UISwipeGestureRecognizer

With UISwipeGestureRecognizer implemented in this tutorials, you could swipe through a bunch of images. With the example below, I’ve attached 2 additional images which is duck and bird. The arrangement of the images are stored in an array. The arrangement in an array always begin with 0 instead of 1. 

In the example below, this is how it look like when swiping takes place.

  1. Drag another Image View onto the Main.storyoard and set a chicken as it’s image
  2. Drag 2 Swipe Press Gesture Recognizer onto the image and control + drag Long Press Gesture Recognizer to View Controller and click on the action. (Make sure you have the IBAction method written). Make sure that there is Right & Left swipe.

3. Write the code

var index = 0
@IBAction func swipeGesture(recognizer: UISwipeGestureRecognizer){
    var images = ["chicken","duck","bird"]
        
    if let move = recognizer as? UISwipeGestureRecognizer {
        switch move.direction {
        case UISwipeGestureRecognizerDirection.right:
            index += 1
            if index > images.count - 1 {
                index = 0
            }
            secondImageView.image = UIImage(named: images[index])
        case UISwipeGestureRecognizerDirection.left:
            index -= 1
            if index < 0 {
                index = images.count - 1
            }
            secondImageView.image = UIImage(named: images[index])
        default:
            break
        }
    }
}

 

The projects can be found on Github

  • Article By :
    Founder of DaddyCoding. Studied Computer Science, Information System and Information Technology at BYU-Hawaii. Currently spending most of my time researching and learning on helping to expose making iOS apps.

Random Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*