Skip to content

Instantly share code, notes, and snippets.

@giusecapo
Last active August 24, 2017 08:40
Show Gist options
  • Save giusecapo/b9d86faa801e3ab6cc7a03a575be0c46 to your computer and use it in GitHub Desktop.
Save giusecapo/b9d86faa801e3ab6cc7a03a575be0c46 to your computer and use it in GitHub Desktop.
A swift function to show a view or a view controller everywhere. Useful if you need to show a view from outside of a controller!
class ShowEverywhere{
var view: UIView?
var viewController: UIViewController?
init(view: UIView){
self.view = view
self.viewController = nil
}
init(viewController: UIViewController) {
self.viewController = viewController
self.view = nil
}
func show(){
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let appWindow = appDelegate.window
var topViewController = appWindow?.rootViewController
while topViewController?.presentedViewController != nil {
topViewController = topViewController?.presentedViewController
}
if let viewToShow = self.view {
viewToShow.alpha = 0.0
topViewController?.view.addSubview(viewToShow)
UIView.animate(withDuration: 0.2) {
viewToShow.alpha = 1.0
}
}
if let viewControllerToShow = self.viewController {
topViewController?.present(viewControllerToShow, animated: true, completion: nil)
}
}
}
// USAGE:
// ShowEverywhere(myView/myViewController).show()
// Have fun!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment