-4

So on Snapchat you swipe left to go to chats, and right to go to stories/discover. How can I implement this into my app? Does SwiftUI have this capability with DragGesture()? Or does only UIKit have this and what would the code be please?

lewis
  • 2,936
  • 2
  • 37
  • 72

2 Answers2

0

It is definitely possible in swiftUI, but I am not familiar enough to verbalize so I will answer with UIKit since you have implied that UIKit an acceptable answer for you as well.

Here is conceptually one way to do it in UIKit

Add a gesture recognizer to your view. You can see how to do that here:

How to programmatically send a pangesture in swift https://developer.apple.com/documentation/uikit/uiview/1622496-addgesturerecognizer

Add a second view to the right or left of your view. Animate the second view to move based on the movement, and location of the touch.

You could also just have a gesture recognizer that performs a custom segue that animates. Have a custom segue for each direction with a left and right animation navigating to different viewcontrollers.

https://www.appcoda.com/custom-segue-animations/

ekrenzin
  • 387
  • 2
  • 12
-1

In Swift, you can accomplish this by code similar to this:

  // First declare and initialize each swipe gesture you want to create.  I have added swipe left and right, to go back and forth between views.

   let rightSwipe : UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe(sender:)))
   rightSwipe.direction = .right

   let leftSwipe : UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe(sender:)))
   leftSwipe.direction = .left

Next you want to handle each swipe, inside a function.

@objc func handleSwipe(sender: UISwipeGestureRecognizer) {

     if sender.direction == .right { // user swiped right
          // push view controller (push new view on the navigation stack)
          self.navigationController?.pushViewController(viewController(), animated: true)

     } else { // user swiped left
          // pop view controller (go back one view on the navigation stack)
          self.navigationController?.popViewController(animated: true)

     }
}
drfalcoew
  • 615
  • 5
  • 14