Inside of my main window's root view controller class, I have set a UITapGestureRecognizer property. I've added this property to an image property through the addGestureRecognizer method during the call to the overridden viewDidLoad function. I have also set image.isUserInteractionEnabled to true.
override func viewDidLoad() {
image.addGestureRecognizer(tap)
image.isUserInteractionEnabled = true
self.view.addSubview(image)
}
var tap = UITapGestureRecognizer(target: self, action: #selector(imagePressed(_ :)))
Sadly, this does not result in imagePressed() being called when run. What's confusing me is the fact that the following code produces the intended result.
override func viewDidLoad() {
var tap = UITapGestureRecognizer(target: self, action:#selector(imagePressed(_ :)))
image.addGestureRecognizer(tap)
image.isUserInteractionEnabled = true
self.view.addSubview(image)
}
So my question is, why does the UITapGestureRecognizer's selector not get invoked during the first case?
Using Swift 3 and Xcode 8.2.1
I think the problem here is addGestureRecognizer
.
Try to change your viewDidLoad
to:
override func viewDidLoad() {
var tap = UITapGestureRecognizer(target: self, action:#selector(imagePressed(_ :)))
image.isUserInteractionEnabled = true
self.view.addSubview(image)
image.addGestureRecognizer(tapGesture)
}
For future readers:
The first case does not work because tap
is instantiated before the view controller's view is loaded, despite being written after the function declaration. Before viewDidLoad()
is called, self.view
is nil
, and because UITapGestureRecognizer
relies on the view, the gesture recognizer doesn't work.
Main takeaway: Both create and add gesture recognizers after your view controller's view has been added to the view hierarchy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With