为什么 Xcode 不允许我使用 presentViewController?

Why doesn't Xcode allow me to use presentViewController?

我想在我的 SpriteKit 游戏中实现一个分享功能。我有一个按钮,我正在尝试在 Gamescene 中执行此操作。这是我为此找到的代码:

func handleTwitter(sender: AnyObject) {
// Check if Twitter is available
if(SLComposeViewController.isAvailableForServiceType(SLServiceTypeTwitter)) {
// Create the tweet
let tweet = SLComposeViewController(forServiceType: SLServiceTypeTwitter)
tweet.setInitialText("I want to share this App: ")
tweet.addImage(UIImage(named: "shareImage"))
self.presentViewController(tweet, animated: true, completion: nil)

看起来很合乎逻辑,但我遇到了问题

self.presentViewController(tweet, animated: true, completion: nil)

Xcode 告诉我 GameScene doesn't have a member called "presentViewController"。我是否只需要在 GameViewController.swift 中实现此代码?如果是这样,我将如何在游戏场景和其他场景中使用它?我有两个带有共享按钮的场景。或者问题出在 SLComposeViewController?我不明白这是什么问题,我是否需要在 GameScene 中声明某种委托才能使其正常工作?

这是适合我的代码。

UIViewController *vc = self.view.window.rootViewController;
[vc presentViewController:tweet animated:YES completion:nil];

希望对您有所帮助

所以对于那些遭受该问题困扰的人。答案是:

func handleTwitter() 应该在 GameViewController。然后在 viewDidLoad 你需要 post 一个 NSNotification:

NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleTwitter", name: "tweet", object: nil)
//You can use any name in the name field
//selector should be the name of a function without braces
//that you want to pass to other scenes

然后你应该转到你的 GameScene 或 GameOverScene 或其他任何地方并创建一个响应 NSNotification 的全局函数:

func gameOvetTweet() {
    NSNotificationCenter.defaultCenter().postNotificationName("tweet", object: nil)
}
//make sure that name in 'postNotificationName("THIS NAME"...' 
//is matching name that you've passed in GameViewController.
//In this example it is "tweet"

然后,唯一剩下要做的就是 post 您的函数随心所欲。例如:

if self.nodeAtPoint(location) == self.twitterButton {
          gameOverTweet()
        } 

就是这样。我也用它来做广告。

任何使用 swift 的人: self.view?.window?.rootViewController!.presentViewController(viewController!, animated: true, completion: nil)