Skip to content

Instantly share code, notes, and snippets.

@pjechris
Created May 18, 2020 08:49
Show Gist options
  • Save pjechris/a3389a10cdbab3f1f1417b5ae8866863 to your computer and use it in GitHub Desktop.
Save pjechris/a3389a10cdbab3f1f1417b5ae8866863 to your computer and use it in GitHub Desktop.
Dimming controller
/// Dimming presenter
/// Code is mostly coming from apple doc: https://developer.apple.com/documentation/uikit/uipresentationcontroller
class DimmingPresentationController: UIPresentationController {
private let backgroundColor: UIColor
private lazy var dimmingView: UIView = {
let view = UIView()
view.backgroundColor = backgroundColor
view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(onTapped)))
return view
}()
init(presentedViewController: UIViewController,
presenting presentingViewController: UIViewController?,
backgroundColor: UIColor) {
self.backgroundColor = backgroundColor
super.init(presentedViewController: presentedViewController, presenting: presentingViewController)
}
override open func presentationTransitionWillBegin() {
let transitionCoordinator = presentingViewController.transitionCoordinator
super.presentationTransitionWillBegin()
guard let containerView = containerView else {
return
}
dimmingView.frame = containerView.bounds
dimmingView.alpha = 0
containerView.addSubview(dimmingView)
transitionCoordinator?.animate(alongsideTransition: { _ in self.dimmingView.alpha = 1 },
completion: nil)
}
override open func presentationTransitionDidEnd(_ completed: Bool) {
super.presentationTransitionDidEnd(completed)
if !completed {
dimmingView.removeFromSuperview()
}
}
override open func dismissalTransitionWillBegin() {
let transitionCoordinator = presentingViewController.transitionCoordinator
super.dismissalTransitionWillBegin()
transitionCoordinator?.animate(alongsideTransition: { _ in self.dimmingView.alpha = 0 },
completion: nil)
}
override open func dismissalTransitionDidEnd(_ completed: Bool) {
super.dismissalTransitionDidEnd(completed)
if completed {
dimmingView.removeFromSuperview()
}
}
@objc
private func onTapped() {
presentingViewController.dismiss(animated: true, completion: nil)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment