从SKScene获取UIViewController

时间:2017-08-03 16:19:57

标签: ios swift uiviewcontroller sprite-kit

据我所知,UIViewController管理与界面的交互,例如转换,而View只是一个对象,一个上下文的容器。 因此,我对如何获取SKScene的UIViewController感到困惑

我正在尝试将 Google移动广告实施到我的项目中:

interstitial.present(fromRootViewController: /* UIViewController */)

但是,其中一个参数需要一个UIViewController对象。我已经看了一些其他不同的问题,但大多数都有点过时,在Objective-c中。 有没有人对获取SKScene的UIViewController的最佳方法有任何建议

这是我正在初始化插页式广告的方法:

override func didMove(to view: SKView) {

        interstitial = GADInterstitial(adUnitID: "code")
        let request = GADRequest()
        interstitial.load(request)

        if interstitial.isReady {
        //    interstitial.present(fromRootViewController: /* UIViewController */)
        } else {
            print("Ad wasn't ready")
        }

        self.anchorPoint = CGPoint(x: 0.5, y: 0.5)
        self.backgroundColor = UIColor(red:0.17, green:0.24, blue:0.31, alpha:1.0)
        self.physicsWorld.gravity = CGVector(dx: 0, dy: 0)
    }

2 个答案:

答案 0 :(得分:2)

您的视图控制器是:

  

self.view?.window?.rootViewController

示例:

        let isReady = GADRewardBasedVideoAd.sharedInstance().isReady          
        guard let controller = self.view?.window?.rootViewController as? GameViewController else {return}

        if isReady {
            print("ADMOB: started")
            GADRewardBasedVideoAd.sharedInstance().present(fromRootViewController: controller)
        }

答案 1 :(得分:1)

在您的skscene上声明VC并在View Controller上将其设置为self。像这样:

SKScene

  var viewController: myViewController!

override func didMove(to view: SKView) {

        viewController.myVariable = 10


}

查看控制器

class myViewController: UIViewController, SKSceneDelegate {

    var scene: GameScene!

var myVariable: Int

    override func viewDidLoad() {
        super.viewDidLoad()

        skView.presentScene(scene)
        scene.viewController = self
        }