A common way to dismiss a modal is to swipe down - How do we allows the user to drag the modal down, if it's far enough, the modal's dismissed, otherwise it animates back to the original position?
For example, we can find this used on the Twitter app's photo views, or Snapchat's "discover" mode.
Similar threads point out that we can use a UISwipeGestureRecognizer and [self dismissViewControllerAnimated...] to dismiss a modal VC when a user swipes down. But this only handles a single swipe, not letting the user drag the modal around.
Swift 4.x, Using Pangesture
Simple way
Vertical
Helper function
Hard way
Refer this -> https://github.com/satishVekariya/DraggableViewController
I'll share how I did it in Swift 3 :
Result
Implementation
Where the Modals View Controllers inherit from a
class
that I've built (ViewControllerPannable
) to make them draggable and dismissible when reach certain velocity.ViewControllerPannable class
In Objective C : Here's the code
in
viewDidLoad
Massively updates the repo for Swift 4.
For Swift 3, I have created the following to present a
UIViewController
from right to left and dismiss it by pan gesture. I have uploaded this as a GitHub repository.DismissOnPanGesture.swift
file:Easy usage:
I've created an easy to use extension.
Just inherent Your UIViewController with InteractiveViewController and you are done InteractiveViewController
call method showInteractive() from your controller to show as Interactive.
I just created a tutorial for interactively dragging down a modal to dismiss it.
http://www.thorntech.com/2016/02/ios-tutorial-close-modal-dragging/
I found this topic to be confusing at first, so the tutorial builds this out step-by-step.
If you just want to run the code yourself, this is the repo:
https://github.com/ThornTechPublic/InteractiveModal
This is the approach I used:
View Controller
You override the dismiss animation with a custom one. If the user is dragging the modal, the
interactor
kicks in.Dismiss Animator
You create a custom animator. This is a custom animation that you package inside a
UIViewControllerAnimatedTransitioning
protocol.Interactor
You subclass
UIPercentDrivenInteractiveTransition
so that it can act as your state machine. Since the interactor object is accessed by both VCs, use it to keep track of the panning progress.Modal View Controller
This maps the pan gesture state to interactor method calls. The
translationInView()
y
value determines whether the user crossed a threshold. When the pan gesture is.Ended
, the interactor either finishes or cancels.