我想在游戏过程中调用共享功能。我有一些我可以在我的GameViewController中使用的代码
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 Class中设置了ViewController ......
var viewController: GameViewController!
...并在我的ViewController
中将scene.viewController设置为selfclass 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中,它给了我一个"在打开一个可选值&#34时找到了nil;错误。
我想我可能需要稍后将scene.viewController设置为self,但我不知道如何在viewController中执行此操作。
非常感谢任何帮助。
答案 0 :(得分:1)
首先,您在scene.viewController
之后不需要问号。
其次,scene.viewController = self
应该之前 skView.presentScene(scene)
。这可能会解决您的问题。
最后,它被认为是糟糕的设计(或至少草率)使SKScene具有UIViewController的属性。场景类现在与使用UIViewController相关联,如果你想将你的代码扩展到没有使用UIViewController来控制视图的东西(例如你想制作游戏的Mac版本),它就会赢得#39 ;因为它的硬编码与UIViewController一起使用,所以马上工作。
"纯粹"这样做的方法是一种名为" delegation"由iOS程序员。您创建一个将成为您的委托的协议,并使您的视图控制器实现该协议。然后SKScene使用协议,而不是UIViewController。
所有这一切,你可能想要忽略这种复杂性。
答案 1 :(得分:-1)
我在GameViewController中搜索如何从GameScene调用函数时发现了你的问题,如下所示:
@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()
}