Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITapGestureRecognizer selector not being invoked

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

like image 692
modest_mildew Avatar asked Apr 12 '17 02:04

modest_mildew


2 Answers

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)
}
like image 132
Luan Tran Avatar answered Nov 16 '22 14:11

Luan Tran


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.

like image 41
throwaway390384085 Avatar answered Nov 16 '22 16:11

throwaway390384085