kuzdu kuzdu - 1 year ago 76
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() {

let panRec = UIPanGestureRecognizer()
panRec.addTarget(self, action: #selector(ViewController.draggedView(_:)))
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.userInteractionEnabled = true


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

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

let sidemenu = Tools()

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 Source

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:


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download