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?
-
2What have you tried so far? – Aaron Franke Oct 29 '19 at 16:22
-
Nothing, I'm just researching trying to find how to do it on swiftUI or UIKit and I can't find anything – John Johnny Oct 29 '19 at 19:30
2 Answers
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.

- 387
- 2
- 12
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)
}
}

- 615
- 5
- 14