Reputation: 1213
I've got buttons I'm creating on my view when the page is loaded.
In my viewDidAppear I've got
NotificationCenter.default.addObserver(self, selector: #selector(self.didDoubleTapOnACircle(sender:)), name: .didDoubleTap , object: nil)
These are listening to notifications set up in the view's custom class. For example :
func doubleTapAction(sender : UIButton) {
print("Double tapped")
NotificationCenter.default.post(name: .didDoubleTap , object: nil, userInfo: ["tagTapped" : self.tag])
}
and then I've got
let doubleTap = UITapGestureRecognizer(target: self, action: #selector(self.doubleTapAction(sender:)))
doubleTap.numberOfTapsRequired = 2
self.addGestureRecognizer(doubleTap)
So this all works on initial load. On my main view when I double tap on one of these views the function I've got runs once and does exactly what's expected. This code has worked for months now and out of nowhere it has started to run twice if I leave and come back to the page. It doesn't matter how many times I leave and come back, it caps out at running twice.
What's confusing is in my doubleTapAction I have the printout of "Double tapped"), but in my function I'm calling in my mainVC didDoubleTapOnACircle, I've got a printout and that gets printed twice. The gesture recognizer is only getting "recognized" one time, but the actual function is being called twice.
In my viewWillDissapear I've got
NotificationCenter.default.removeObserver(self, name: .didDoubleTap, object: nil)
This is happening on every single one of my gesture recognizer functions. The page loads for the first time, it all runs once. If I leave, they all start running twice, but the printout on the actual class's function like doubleTapAction gets printed once.
Any ideas?
Upvotes: 1
Views: 1094
Reputation: 5554
Move the tap gesture code into viewDidLoad
and not viewDidAppear
let doubleTap = UITapGestureRecognizer(target: self, action: #selector(self.doubleTapAction(sender:)))
doubleTap.numberOfTapsRequired = 2
self.addGestureRecognizer(doubleTap)
viewDidAppear
will be called every time you go back to that screen. You don't need to remove the gesture recognisers when you move to a different screen - they will only be called when that view is visible.
Upvotes: 3