unwindSegue无法传递数据(Swift - Xcode)

时间:2018-01-30 11:03:44

标签: ios swift segue nsuserdefaults

我正在使用UserDefaults存储和检索我的数据,但我不知道为什么当我执行展开segue时,我的userdefaults数据无法传递给下一个视图控制器,但如果我执行正常推送segue,我的userdefaults数据可以在下一个viewcontroller中看到。

P.S:仅self.performSegue(withIdentifier: "unwindSegue", sender: nil)是unwindSegue。

FirstViewController

@IBAction func Button1(_ sender: Any) {
    var i: Int = 0
    let randomNumber = arc4random_uniform(3) + 1
    i = Int(randomNumber)

    let alert = AlertController(title: "Congratualations", message: "You earned \(i) tokens!", preferredStyle: .alert)
    alert.setTitleImage(UIImage(named: "token"))
    // Add actions
            alert.addAction(UIAlertAction(title: "Let's See!", style: UIAlertActionStyle.default, handler: { (action) in
                var returnValue: Int = UserDefaults.standard.integer(forKey: "tokens")
                returnValue = returnValue + i;
                UserDefaults.standard.set(returnValue, forKey:"tokens")
                self.performSegue(withIdentifier: "unwindSegue", sender: nil)
                }))
        if (returnValue != 30){
            alert.addAction(UIAlertAction(title: "Continue Playing", style: UIAlertActionStyle.default, handler:    { (action) in
                var returnValue: Int = UserDefaults.standard.integer(forKey: "tokens")
                returnValue = returnValue + i;
                UserDefaults.standard.set(returnValue, forKey:"tokens")
                self.performSegue(withIdentifier: "continue", sender: self)
                }))
        }
    self.present(alert, animated: true, completion: nil)
}

SecondViewController

import UIKit

class TokenController: UIViewController {
    @IBOutlet var tokens: UILabel!
    @IBOutlet var minus1: UIButton!
    @IBOutlet var minus2: UIButton!
    var returnValue: Int = UserDefaults.standard.integer(forKey: "tokens")

    override func viewDidLoad() {
        super.viewDidLoad()
        tokens.text = "x\(returnValue)"
    }

@IBAction func unwindSegue(_ sender: UIStoryboardSegue) {
}

enter image description here enter image description here

2 个答案:

答案 0 :(得分:2)

@Kinja请参考此网址以使用unwind segue

  

点击此处: - Perform action when segue is closed

答案 1 :(得分:1)

因为当您执行Push的新ViewController时,会将其加载到内存中,并调用方法“ViewDidLoad”。 当您执行展开segue时,之前的ViewController已经在内存中,因此不会调用viewDidLoad和所有初始化,并且不会更新标签和所有图形。 这不是问题,因为您可以通过变量sender来访问unwindSegue实现中所需的所有数据。见这个例子:

func unwindToViewController(segue: UIStoryboardSegue) {
        let vc_source = segue.source as! SecondViewController
        self.myLabel.text! = vc_sorgente.myTextField.text!      
}