I need to add a left swipe gesture recognizer to my CommentVC
. My CommentVC
includes a tableView
, so if I have 0 cells in CommentVC
then I am unable to swipe back.
My code: with this code I can swipe only if there at least one cell in that area of that tableview. But I need to swipe if there is no cell as well. How can I achieve that? Please guide me.
class CommentVC: UIViewController, UIGestureRecognizerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.interactivePopGestureRecognizer?.delegate = self
self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true
let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(self.respondToSwipeGesture))
swipeRight.direction = UISwipeGestureRecognizer.Direction.left
self.tableView.addGestureRecognizer(swipeRight)
}
@objc func respondToSwipeGesture(gesture: UIGestureRecognizer) {
if let swipeGesture = gesture as? UISwipeGestureRecognizer {
switch swipeGesture.direction {
case UISwipeGestureRecognizer.Direction.left:
print("Swiped left")
self.navigationController?.popViewController(animated: true)
default:
break
}
}
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
I just tried this and its completely worked. i have just changed one line
self.tableView.addGestureRecognizer(swipeRight)
above line i have replaced above line with this line. then able to swipe with no cells and with cells in tableview i have added a UISwipeGestureRecognizer to the superview that contains the UITableView
self.view.addGestureRecognizer(swipeRight)
this is total code:
class CommentVC: UIViewController, UIGestureRecognizerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.interactivePopGestureRecognizer?.delegate = self
self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true
let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(self.respondToSwipeGesture))
swipeRight.direction = UISwipeGestureRecognizer.Direction.left
self.view.addGestureRecognizer(swipeRight)
}
@objc func respondToSwipeGesture(gesture: UIGestureRecognizer) {
if let swipeGesture = gesture as? UISwipeGestureRecognizer {
switch swipeGesture.direction {
case UISwipeGestureRecognizer.Direction.left:
print("Swiped left")
self.navigationController?.popViewController(animated: true)
default:
break
}
}
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}