Reputation: 27
After I click on a button I go to a new view controller.
I made it possible to make points with var score = 0
in a IBOutlet and to show to points I use Score.text = "\(++score)"
.
How can I pass the score to the 'Game over' screen/view controller to a label called "resultScore"?
Upvotes: 1
Views: 1422
Reputation: 3908
Add an attribute secondViewController
in the destination view controller, and use prepareForSegue
Current View Controller
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
if (segue.identifier == "segueTest") {
var svc = segue!.destinationViewController as secondViewController;
svc.toPass = textField.text
}
}
in secondViewController
you can define one variable like String
var toPass:String!
In the secondViewController
under the viewDidLoad
function add this code
println(\(toPass))
Upvotes: 4
Reputation: 14329
FirstViewController
@IBOutlet weak var textField: UITextField!
...
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let vc = segue.destinationViewController as? GameOverViewController {
vc.score = Int(textField?.text)
}
}
...
SecondViewController
var score: Int!
@IBOutlet weak var label: UILabel!
...
override func viewDidLoad() {
super.viewDidLoad()
label.text = String(score)
}
This method will call when button was pressed, and in this place you may set some properties for your second view controller
Upvotes: 0
Reputation: 71854
One easy way to achieve that is you can use NSUserDefault
for that.
first of all in your playScene
when you are increasing your score you can store your score this way:
Score.text = "\(++score)"
NSUserDefaults.standardUserDefaults().setInteger(score, forKey: "userScore")
After that in your next view controller you can get score this way:
resultScore = NSUserDefaults.standardUserDefaults().integerForKey("userScore")
Remember that type of your resultScore
should be Int
.
Upvotes: 0