Search code examples
iosswiftuipangesturerecognizer

which is lighter on the client?: UIPanGestureRecogizer continuous listening or adding and removing when needed


So I'm making a messaging app that allows the user to hide the keyboard on pan, with a UIPanGestureRecognizer. I only want the user to hide the keyboard on vertical pan, only when the keyboard is showing. Here is my code:

let panGesture = UIPanGestureRecognizer(target: self, action: #selector(viewPanned(_:)))
panGesture.minimumNumberOfTouches = 1
panGesture.maximumNumberOfTouches = 1
panGesture.delegate = self
self.view.addGestureRecognizer(panGesture)

So my question is:

Which option gives a lighter workload to the app?

  1. Adding the UIPanGestureRecognizer on viewDidLoad, so whenever the user pans, viewPanned is called, even when the keyboard isn't showing, and it checks whether or not the keyboard is showing, or
  2. Every time the keyboard shows, add the panGesture to the main view, and every time it hides, remove the panGesture from the main view, like so.

    self.view.removeGestureRecognizer(panGesture) panGesture.delegate = nil


Solution

  • It really depends on how frequently you show the keyboard ,if you show it a lot such in sign up form it's better to add it in viewDidLoad instead of taking time (in milliseconds) to add & remove the pan , otherwise do that add / remove approach , besides it's a trade of between executing (cpu cycles) and memory (add/remove)