-1

I'm trying to create my first Cocoapod framework, and need to attach a simple UITapGestureRecognizer to a view, but I can't get the tap gesture action to be called from within my framework. I've got:

class ViewController: UIViewController {

    override func viewDidLoad() {
         super.viewDidLoad()

        let foo = Foo()
        foo.attachTo(view: view)
    }
}

I created a framework using pod lib create Foo, inside is

public class Foo {
    public init() {}

    public func attachTo(view: UIView) {
        let endpointGesture = UITapGestureRecognizer(target: self, action: #selector(selected(_:)))
        view.backgroundColor = UIColor.blue
        view.isUserInteractionEnabled = true
        view.addGestureRecognizer(endpointGesture)
    }

    @objc private func selected(_ sender: UITapGestureRecognizer) {
        print("Gesture Recognized")
    }
}

I can tell the view is correctly passed into the framework because building the app gives me a blue screen.

Moving the gesture recognizer and selected function into ViewController works as expected as well. Tapping on the view prints Gesture Recognized to the console, so there's something going on with the framework I don't understand.

I have already tried adding the -ObjC linker flag to the framework, but that doesn't seem to have done anything. Am I missing something?

Shrines
  • 3
  • 1
  • 1
  • The code you posted looks good, and it appears you know that also. Generally a gesture in a framework is meant to trigger something more than `print` - in my use cases a message to a delegate. Two thoughts: (1) If you set a breakpoint on the `print` statement, does it hit it? (2) If it does, can you either (a) create a protocol/delegate setup to your view controller or (b) refactor (for testing things out) things into a `UIButton` to see what's going on? It really looks like your `print` isn't getting hit. –  Mar 26 '18 at 22:49
  • Lack of relevant tags... – El Tomato Mar 26 '18 at 22:55
  • @dfd Setting a breakpoint doesn't seem to be doing anything, which leads me to believe the selector is never getting called. I tried creating a protocol/delegate anyways but it didn't call `selected` as expected. – Shrines Mar 27 '18 at 15:39

1 Answers1

0

The problem is that your foo variable is not retained. If you make the foo variable as instance variable it should work.

class ViewController: UIViewController {

    let foo = Foo() // this is now retained by the view controller

    override func viewDidLoad() {
        super.viewDidLoad()

        foo.attachTo(view: view)
    }
}
Rico Crescenzio
  • 3,952
  • 1
  • 14
  • 28