首页 文章

使用segue在View Controllers之间保存变量

提问于
浏览
-2

我使用Swift和Xcode 6.4,我想使用Segue将变量从一个View Controller传递给另一个 . 当您按下按钮时,变量持续时间应该为ViewController2提供值 . 在ViewController2中,我想再次使用此变量 .

Main.storyboard按钮标识符名为Test1

我怎样才能做到这一点?你能用我的代码帮我吗?怎么了?

谢谢

代码ViewController1:

导入UIKit

class 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
    }
}

}

代码ViewController2:

导入UIKit

class ViewController2:UIViewController {

var duration:Double?

var result = duration + 2.0
println(\(result))

override func viewDidLoad() {
    super.viewDidLoad()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

}

1 回答

  • 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
        }
    }
    

相关问题