I'm trying to assign a value to a variable when a button is pressed and then send it to my second viewcontroller.
I'm having trouble passing a variable (int) from my first viewcontroller(FirstViewController.swift) to my secondcontroller(ViewController.swift).
My entry point is FirstViewController.swift
This is my FirstViewController.swift code:
import UIKit
var language:Int = 0
class FirstViewController: UIViewController {
@IBAction func dutch(sender: AnyObject) {
language = 1
println(language)//check in console
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
var soundsVC = segue.destinationViewController as! ViewController
soundsVC.languageSelected = language
}
The @IBAction func dutch gets activated when a button is pressed, after that has happened it should change the value of language to 1.
import UIKit
import AVFoundation
class ViewController: UIViewController {
var languageSelected:Int = 0
@IBAction func controleFunc(sender: AnyObject) {
println(languageSelected)
println(language)
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor(patternImage: UIImage(named: "background.jpg")!)
// Do any additional setup after loading the view, typically from a nib.
println(languageSelected)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
My output is:
0 //languageSelected
1 //language
0 //languageSelected if the controle function is activated (controleFunc)
1 //language if the controle function is activated (controleFunc)
I just started learning Swift, so I don't really know why languageSelected won't take the value of language. Is it because I declare languageSelected:Int = 0 at the top of ViewController.swift? I have tried to change that to languageSelected:Int = language, but unfortunately I had the same results.
Thanks! Sezer
viewDidLoad()is happening before theprepareForSegue(), if you want to use the state that's passed in, either override the setter (as below) and do something with it, or do it inviewWillAppear()