如何在Swift中的两个场景之间传递数据? [英] How do I pass data between two scenes in Swift?
问题描述
我有两个场景,我想使用segue将单个变量传递给另一个场景。我试过但不幸的是我见过的所有教程都在处理故事板。我没有使用故事板。我正在以编程方式完成所有这些。
I have two scenes where I would like to pass a single variable to another scene using a segue. I have tried but unfortunately all tutorials I have seen are dealing with the storyboard. I am not using the storyboard. I am doing all of this programatically.
这是我想要初始化的segue:
Here is the segue i am trying to initialize:
func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
if (segue.identifier == "segueTest") {
var lose = segue.destinationViewController as! loserScene;
lose.toPass = scoreLabelNode.text
}
}
失败者场景是我的第二个场景。
scoreLabelNode.text是我用作分数的NSTimer的文本。
The Loser Scene is my second scene.
scoreLabelNode.text is the text of an NSTimer which i'm using as a score.
我想将scoreLabelNode.text移动到另一个场景,这是我的loserScene。
I want to move the scoreLabelNode.text into another scene which is my loserScene.
我的loserScene设置如下:
My loserScene is set up like this:
import SpriteKit
import Foundation
let GameOverLabelCategoryName = "gameOverLabel"
class loserScene: SKScene {
var toPass: String!
var scoreLabel = SKLabelNode(fontNamed:"[z] Arista Light")
override func didMoveToView(view: SKView) {
var gameOver = SKSpriteNode(imageNamed: "gameover.png")
gameOver.position = CGPoint(x: self.frame.size.width/2, y: self.frame.size.height/2)
self.addChild(gameOver)
println(toPass)
}
}
我正在尝试打印'toPass'来测试字符串segue,但我只是没有。
I am trying to print 'toPass' to test the string segue, but I just get nil.
推荐答案
好的!所以不要使用segue。你不能用SKSCENE做什么。我使用了一个结构。我把结构放在我想要传递数据的场景之外,并确保将数据输入到结构中。然后我从另一个场景中访问了该结构,它完美地运行了!
OK! So instead of using a segue. WHICH YOU CANNOT DO WITH AN SKSCENE. I used a struct. I put the struct outside of one of my scenes that I wanted data to be passed from, and made sure the data was being fed into the struct. I then accessed the struct from another scene and it works perfectly!
struct Variables {
static var aVariable = 0
}
这是结构^我将它设置为0但它会自动更新在比赛结束时记录得分。
然后我在另一个场景中访问它:
this is the struct^ I have it set to 0 but it will be updated automatically when the score is recorded at the end of the run of my game. I then accessed it like so in another scene:
print(Variables.aVariable)
这将在我的新场景中打印结构中的变量。我也可以将这个结构转换为字符串并将其用于labelnode。
This prints the variable from the struct in my new scene. I can also turn this struct into a string and use it for a labelnode.
这篇关于如何在Swift中的两个场景之间传递数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!