Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save egzonpllana/242eadef735fd03ba11c52acce9e7e44 to your computer and use it in GitHub Desktop.
Save egzonpllana/242eadef735fd03ba11c52acce9e7e44 to your computer and use it in GitHub Desktop.
Drag down view controller to dismiss. Swift 5
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