Created
October 5, 2020 06:15
-
-
Save egzonpllana/242eadef735fd03ba11c52acce9e7e44 to your computer and use it in GitHub Desktop.
Drag down view controller to dismiss. Swift 5
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
override func viewDidLoad() { | |
super.viewDidLoad() | |
let gestureRecognizer = UIPanGestureRecognizer(target: self, | |
action: #selector(panGestureRecognizerHandler(_:))) | |
view.addGestureRecognizer(gestureRecognizer) | |
} | |
@IBAction func panGestureRecognizerHandler(_ sender: UIPanGestureRecognizer) { | |
let touchPoint = sender.location(in: view?.window) | |
var initialTouchPoint = CGPoint.zero | |
switch sender.state { | |
case .began: | |
initialTouchPoint = touchPoint | |
case .changed: | |
if touchPoint.y > initialTouchPoint.y { | |
view.frame.origin.y = touchPoint.y - initialTouchPoint.y | |
} | |
case .ended, .cancelled: | |
if touchPoint.y - initialTouchPoint.y > 200 { | |
dismiss(animated: true, completion: nil) | |
} else { | |
UIView.animate(withDuration: 0.2, animations: { | |
self.view.frame = CGRect(x: 0, | |
y: 0, | |
width: self.view.frame.size.width, | |
height: self.view.frame.size.height) | |
}) | |
} | |
case .failed, .possible: | |
break | |
} | |
} | |
/* | |
When viewcontroller is half or smaller from normal fixed size | |
*/ | |
// @IBOutlet weak var pickerContentView: UIView! | |
@IBAction func panGestureRecognizerHandler(_ sender: UIPanGestureRecognizer) { | |
guard let rootView = view, let rootWindow = rootView.window else { return } | |
let rootWindowHeight: CGFloat = rootWindow.frame.size.height | |
let touchPoint = sender.location(in: view?.window) | |
var initialTouchPoint = CGPoint.zero | |
let blankViewHeight = (rootWindowHeight - pickerContentView.frame.size.height) | |
let dismissDragSize: CGFloat = 200.00 | |
switch sender.state { | |
case .began: | |
initialTouchPoint = touchPoint | |
case .changed: | |
// dynamic alpha | |
if touchPoint.y > (initialTouchPoint.y + blankViewHeight) { // change dim background (alpha) | |
view.frame.origin.y = (touchPoint.y - blankViewHeight) - initialTouchPoint.y | |
} | |
case .ended, .cancelled: | |
if touchPoint.y - initialTouchPoint.y > (dismissDragSize + blankViewHeight) { | |
dismiss(animated: true, completion: nil) | |
} else { | |
UIView.animate(withDuration: 0.2, animations: { | |
self.view.frame = CGRect(x: 0, | |
y: 0, | |
width: self.view.frame.size.width, | |
height: self.view.frame.size.height) | |
}) | |
// alpha = 1 | |
} | |
case .failed, .possible: | |
break | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment