Search code examples
iosswiftuikit

How to: Give SKScene access to dismiss() UIKit method


Is it possible to get access to dismiss() in an SKScene class? Dismiss is a method available from apples UIKit here is a link to Apple's official documentation on dismiss.

class GameScene: SKScene {

}

Attempting to fire dismiss off from an IBAction example:

    @IBAction func dismissTapped(_ sender: Any) {
     //figure out how to dismiss
    }

Dismiss would normally be used like this -

dismiss(animated: true, completion: nil)

Solution

  • dismiss is a method on UIviewController and not on SKScene. However, your scene does have a view property that is its containing view (which is a SKView, which is a UIView, which is a UIResponder). You can use the view's next method inherited from UIResponder to walk up the responder chain until you hit the first view controller (because UIViewController is also a UIResponder):

    extension UIResponder {
        func firstParent<T: UIResponder>(ofType type: T.Type ) -> T? {
            return next as? T ?? next.flatMap { $0.firstParent(ofType: type) }
        }
    }
    
    //Use in your SKScene like so
    view?.firstParent(ofType: UIViewController.self)?.dismiss(animated: true, completion: nil)