Swipe actions in swift

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? 


How can we make it more easy?

Using a UIViewextension.

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. UIImageViewUIView, …).

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 structand 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<br>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        
        // 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 

But we still need to respond on the swipe actions!

Yup, pseudocode:

@objc func invokeTarget(...) {
    // disamble 
        switch swipeDirection {
        case .up:
        case .down:
        case .left:
        case .right:

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!