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?
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)
}
}