我刚开始使用快速语言,并且知道这个问题是重复的。我已经找到了几个类似的问题和答案,但是我无法找出问题所在。

我想将ScandString变量的值从ScanViewController传递给ResultViewController。

ScanViewcontroller如下:

import UIkit

class ScanViewController: UIViewController  {

    var detectionString : String!

    override func viewDidLoad() {
        super.viewDidLoad()

        detectionString = “SomeDetectedString”
    }

    override func prepareForSegue(segue: UIStoryboardSegue,sender: AnyObject!) {
        if (segue.identifier == "MySegue") {
            var svc = segue.destinationViewController as ResultViewController;
            svc.detectedString = detectionString
        }
    }

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

ResultViewController如下:
import UIkit

class ResultViewController: UIViewController {

    var detectedString: String!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor=UIColor.whiteColor()
        println(detectedString)
    }

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

println(detectedString)没有给我任何结果。问题是如何从ScanViewController获取变量?

最佳答案

这听起来可能很奇怪,但是您的代码没有任何问题,但它不能按原样工作。我同样地使用了您的代码,但忽略了segue。然后,我将ScanViewController嵌入情节提要中的导航控制器中。我还调用了self.performSegueWithIdentifier("MySegue", sender: self)中的ScanViewController viewDidLoad以启动segue。然后,一切都像魅力。您的prepareForSegue很好。 Yuvrajsinh的建议很好,但不是必须的(我在将DetailVC更改为ResultViewController之后尝试了它)。没有导航控制器,将无法正常工作。 segue.identifier是一个字符串,它将在直接的Swift字符串比较中工作。

这是ScanViewController的代码:

import UIkit

class ScanViewController: UIViewController  {

    var detectionString : String!

    override func viewDidLoad() {
        super.viewDidLoad()


        detectionString = "SomeDetectedString"
        println(detectionString)
        self.performSegueWithIdentifier("MySegue", sender: self)
    }

    override func prepareForSegue(segue: UIStoryboardSegue,sender: AnyObject!) {

        if (segue.identifier == "MySegue" || segue.identifier == "SegueFromButton") {
            println("prepareForSegue")
            var svc = segue.destinationViewController as ResultViewController;
            svc.detectedString = detectionString
            println("svc.detectedString: \(svc.detectedString)")
        }
    }

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


}

对于ResultViewController:
import UIkit

class ResultViewController: UIViewController {

    var detectedString: String!

    override func viewDidLoad() {
        println("Result Load View")
        super.viewDidLoad()
        self.view.backgroundColor=UIColor.whiteColor()
        println("detectedString in Result: \(detectedString)")
    }

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

09-06 01:50