DEV Community

Wesley De Groot
Wesley De Groot

Posted on • Originally published at Medium on

Swipe actions in swift

Hi reader,

This is my first post on Medium, if you have any tips please comment.

The issue:

Gestures, delegates, it can be a big struggle (especially for beginners).

If you use a lot of gestures then you’ll need to implement it over and over.

One of the problems is, that code what you write will not apply to other views in your application.

If we use a lot of swipe actions, in different places within our application we want to have reusable code.

But then we see ourselfs overloaded with issues, can it be made more easy?

Yes!

How can we make it more easy?

Using a UIView extension.

Why not a UIViewController?

“Because we also want to support other applications which have a UIView.”

How do we start?

In this post we’ll start with a UIView extension, to make it reusable for other applications (e.g. UIImageView, UIView, …).

In my case it didn’t work on a UITableViewController.

Psuedo code:

import Foundation
import UIKit

extension UIView {
// psuedo code continues

We also need a variable, but simply var myVariable = ... does not work, since we are working in an extension.

There is a workaround, and it may be more easy than you think.

We’ll use a struct and that will solve all our variable problems.

We want to reuse the data, so we make a static var.

Psuedo code:

// .... psuedo code to above blocks
struct gestureClosures {
 static var up = ...
 static var down = ...
 static var left = ...
 static var right = ...
}

We also need to create a function, to make it work!

Psuedo code:

func swipeAction(
 swipeDirection: UISwipeGestureRecognizer.Direction,
 completionHandler: @escaping ()-\>()
 ) {
 // Add a swiper
 let swiper = .... #selector(self.invokeTarget(\_:))
 // give the direction as in swipeDirection
 swiper.direction = swipeDirection

// add to the view 
 self.addGestureRecognizer(swiper)

// save the completionHandler
 switch swipeDirection {
 case .up:
 gestureClosures.up = completionHandler
 case .down:
 gestureClosures.down = completionHandler
 case .left:
 gestureClosures.left = completionHandler
 case .right:
 gestureClosures.right = completionHandler 
 default:
 print("Nothing") 
 } 
}

But we still need to respond on the swipe actions!

Yup, pseudocode:

@objc func invokeTarget(...) {
 // disamble 
 switch swipeDirection {
 case .up:
 gestureClosures.up()
 case .down:
 gestureClosures.down()
 case .left:
 gestureClosures.left()
 case .right:
 gestureClosures.righ() 
 default:
 print("Nothing") 
 }
}

And if we translate it to functional swift code.

Then the output looks similair to above.

The complete solution:

Thanks for reading, if you like this “story” please share!

Any ideas, tips, recommendations?

Please comment!

Discussion (0)