modest_mildew
modest_mildew

Reputation: 73

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

Upvotes: 6

Views: 2382

Answers (2)

throwaway390384085
throwaway390384085

Reputation: 46

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.

Upvotes: 1

Luan Tran
Luan Tran

Reputation: 1142

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

Upvotes: 3

Related Questions