(iOS) Adding Swipe gesture to a view in Swift 4

Adding swipe gesture to a view in Swift 4 (iOS development tutorial) :

In this tutorial, we will learn how to add swipe gesture in iOS applications using swift 4. The swipe gesture can be added to any view. For example, you have one custom notification over your application and you want to remove it if the user swipe from left to right. In that case, we need to add one gesture recognizer on that view. We will add one custom ’view’ and show you how to add all top, bottom, left and right swipe gesture recognizer for that view. Let’s have a look :

Program :

1. Create one sample project and add one View Controller to it. In our project, the name is ViewController.
2. This is the main View controller. Add one custom view to the screen associated with this view controller like below .


3. Create one reference for that view . On our view controller, it is myView.
4. Add UISwipeGestureRecognizer to this view.
5. The type of UISwipeGestureRecognizer can be right, left, up or down.
6. Add all these UISwipeGestureRecognizers to the view using addGestureRecognizer() method.
7. For each recognizer, attach them with different methods. leftSwipe(),rightSwipe(), upSwipe() and downSwipe(). These methods will be called when the user will interact with the view.
8. For each of these recognizers, change the background color of the view.
Let’s take a look at the ViewController’s code :


import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var myView: UIView!
    override func viewDidLoad() {
        let left = UISwipeGestureRecognizer(target : self, action : #selector(ViewController.leftSwipe))
        left.direction = .left
        let right = UISwipeGestureRecognizer(target : self, action : #selector(ViewController.rightSwipe))
        right.direction = .right
        let up = UISwipeGestureRecognizer(target : self, action : #selector(ViewController.upSwipe))
        up.direction = .up
        let down = UISwipeGestureRecognizer(target : self, action : #selector(ViewController.downSwipe))
        down.direction = .down

    func leftSwipe(){
        self.myView.backgroundColor = UIColor.blue
    func rightSwipe(){
        self.myView.backgroundColor = UIColor.green
    func upSwipe(){
        self.myView.backgroundColor = UIColor.yellow
    func downSwipe(){
        self.myView.backgroundColor = UIColor.gray
    override func didReceiveMemoryWarning() {
        // Dispose of any resources that can be recreated.


Run the program and it should look like as below :


Leave a Reply