2015-07-02 33 views
0

我想在遊戲過程中調用共享函數。我有一些代碼,我可以在我的GameViewController如何從GameScene調用viewController中的函數

func showTweetSheet() { 
    let tweetSheet = SLComposeViewController(forServiceType: SLServiceTypeTwitter) 
    tweetSheet.completionHandler = { 
     result in 
     switch result { 
     case SLComposeViewControllerResult.Cancelled: 
      //Add code to deal with it being cancelled 
      break 

     case SLComposeViewControllerResult.Done: 
      //Add code here to deal with it being completed 
      //Remember that dimissing the view is done for you, and sending the tweet to social media is automatic too. You could use this to give in game rewards? 
      break 
     } 
    } 

    tweetSheet.setInitialText("Test Twitter") //The default text in the tweet 
    tweetSheet.addImage(UIImage(named: "TestImage.png")) //Add an image if you like? 
    tweetSheet.addURL(NSURL(string: "http://twitter.com")) //A url which takes you into safari if tapped on 

    self.presentViewController(tweetSheet, animated: false, completion: { 
     //Optional completion statement 
    }) 
} 

我還設置視圖控制器在我GameScene類...

var viewController: GameViewController! 

使用...並設置scene.viewController自我我視圖控制器

class GameViewController: UIViewController { 

override func viewDidLoad() { 
    super.viewDidLoad() 

    if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene { 
     // Configure the view. 
     let skView = self.view as! SKView 
     skView.showsFPS = false 
     skView.showsNodeCount = false 

     /* Sprite Kit applies additional optimizations to improve rendering performance */ 
     skView.ignoresSiblingOrder = true 

     /* Set the scale mode to scale to fit the window */ 
     scene.scaleMode = .AspectFill 

     skView.presentScene(scene) 

     scene.viewController? = self 

    } 
} 

然而,當我打電話,像這樣的功能...

viewController.showTweetSheet() 

...從我的GameScene中,它給了我一個「發現無解包可選值時」錯誤。

我想我可能需要將scene.viewController設置爲稍後,但我不知道如何在viewController中執行此操作。

任何幫助將不勝感激。

+0

使用NSNotifications向VC發送消息以運行方法。 – sangony

+0

@sangony你可以發佈這個答案,因爲這已經回答了這個問題。謝謝。 –

回答

1

首先,你不需要scene.viewController後面的問號。 二,scene.viewController = self應該來之前skView.presentScene(scene)。這可能會解決您的問題。

最後,它被認爲是糟糕的設計(或至少馬虎),使SKScene有一個屬性是UIViewController。場景類現在與使用UIViewController綁定在一起,如果你想將你的代碼擴展到某些不使用UIViewController來控制視圖的東西(例如你想製作一個Mac版的遊戲),它將無法正常工作因爲它的硬編碼與UIViewController一起使用。

完成此操作的「純粹」方式將是iOS程序員稱爲「授權」的技術。你創建一個協議,這將是你的委託,並讓你的視圖控制器實現該協議。然後SKScene使用協議,而不是UIViewController。

所有這一切,你可能想要避開這種複雜性。

0

我已經找到了自己的問題,而搜索如何調用從GameScene在GameViewController一個函數,它是這樣的:

@IBOutlet var gameScene: SKView! 
if let gameSceneAccess = gameScene.scene as? GameScene { 
    gameSceneAccess.functionFromGameScene(params) 
} 

不管怎樣,調用從GameScene你的函數試試這個:

if let controller = self.view?.window?.rootViewController as? GameViewController { 
    controller.showTweetSheet() 
} 
相關問題