kuzdu kuzdu - 3 months ago 12
Swift Question

GestureRecognizer doesnt work dynamic/in extra class swift

I want to implement a gesture recognizer for every Viewcontroller.

The following code is working:

class ViewController: UIViewController {
func draggedView(sender:UIPanGestureRecognizer){
// do stuff
}

override func viewDidLoad() {
super.viewDidLoad()

let panRec = UIPanGestureRecognizer()
panRec.addTarget(self, action: #selector(ViewController.draggedView(_:)))
self.view.addGestureRecognizer(panRec)
self.view.userInteractionEnabled = true
}
}


Now I want give this pan gesture a little bit more dynamic/abstraction

class Tools : NSObject {

var currentViewController: UIViewController?

func addPanToViewController(viewcontroller: UIViewController) {

currentViewcontroller = viewcontroller

if let currentViewcontroller = currentViewcontroller {
let panRec = UIPanGestureRecognizer()
panRec.addTarget(self, action: #selector(draggedView(_:)))
currentViewcontroller.view.addGestureRecognizer(panRec)
currentViewcontroller.view.userInteractionEnabled = true
}

}

func draggedView(sender:UIPanGestureRecognizer) {
//never called
}
}


I call the code in the ViewController-Class like this:

let sidemenu = Tools()
sidemenu.addPanToViewController(self)


But nothing happens. No Error, but no gestures are working. With the debugger I see that the gesture was added. So every code get executed.

I want execute the draggedView inside my Tools class.

I really don't understand where my problem is?

Answer

I think if you want this to work, you have to make the Tools class become singleton with:

static let sharedInstance = Tools()

then in the addPanToViewController:

panRec.addTarget(Tools.sharedInstance, action:#selector(draggedView(_:)))

In your viewController:

Tools.sharedInstance.addPanToViewController(self)