Llg Llg - 11 days ago 8
Swift Question

Swift 3: Back gesture

I have in my Swift 3 application a homeViewController containing a UITableView. When a cell of the table is clicked, then I display a detailViewController. I display it as a child using the

addChildViewController(vc)
. I want to implement the back gesture in order to return to the homeViewController. I want to have the same result as the back mode in the default Mail application of the devices (the back mode to return to the mail's home when I was in the inbox for example). In other words, the gesture allows the user to drag the view from left to right then continuing the left to right drag until the home view is showed, or drag the view from right to left in order to keep the detail view in the whole screen. I tried to do that using the
UIPanGestureRecognizer
but my view goes left and right and sometimes its show the home view from the right side. So in brief, the result that I want is the same as the back gesture functionality of the Mail application.

This is my code:

var rightSwipe: UIPanGestureRecognizer = UIPanGestureRecognizer()
self.rightSwipe = UIPanGestureRecognizer(target: self, action: #selector(self.handleSwipes(_:)))
self.view.addGestureRecognizer(rightSwipe)
func handleSwipes(_ sender: UIPanGestureRecognizer){

if self.rightSwipe.state == .began || self.rightSwipe.state == .changed {

let translation = rightSwipe.translation(in: self.view)
// note: 'view' is optional and need to be unwrapped
//print("translation is : \(translation)")
if(translation.x > 0 && translation.y == 0.0){
self.rightSwipe.view!.center = CGPoint(x: self.rightSwipe.view!.center.x + translation.x, y: self.rightSwipe.view!.center.y + translation.y)
rightSwipe.setTranslation(CGPoint.zero, in: self.view)
}

}
}

Answer

To use NavigationController in your storyboard embeded your HomeViewController with UINavigationController. To embed navigationController select your HomeViewController, in menu choose Editor > Embed In > Navigation Controller.

Now in didSelectRowAt indexPath push the detailViewController.

self.navigationController?.pushViewController(detailVC, animated: true)

If still gesture is not work then in HomeViewController's viewDidLoad set this one.

self.navigationController?.interactivePopGestureRecognizer.isEnabled = true