我使用Swift和Xcode 6.4,我想使用Segue将变量从一个View Controller传递给另一个。 按下按钮时,变量持续时间应该为ViewController2提供值。在ViewController2中,我想再次使用这个变量。
Main.storyboard按钮标识符名为Test1
我该怎么做?你能帮我解决一下我的代码吗?怎么了?
由于
Code ViewController1:
导入UIKit
类ViewController1:UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func ButtonTapped(sender: AnyObject) {
var duration = 1.0
self.performSegueWithIdentifier("Test1", sender: duration)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if (segue.identifier = "Test1") {
let secondViewController = segue.destinationViewController as ViewController2
let duration = sender as Double
secondViewController.duration = duration
}
}
}
Code ViewController2:
导入UIKit
类ViewController2:UIViewController {
var duration:Double?
var result = duration + 2.0
println(\(result))
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
答案 0 :(得分:0)
var duration = Double() // now "duration" is global
@IBAction func ButtonTapped(sender: AnyObject) {
duration = 1.0
self.performSegueWithIdentifier("Test1", sender: duration)
// VVV Any new variable created in this scope will be deallocated
} // HERE
//Then this scope starts...
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if (segue.identifier == "Test1") {
let secondViewController = segue.destinationViewController as ViewController2
// delete this... duration = sender as Double
secondViewController.duration = duration
}
}