小编典典

将一个变量从一个ViewController传递给另一ViewController

swift

我刚开始使用快速语言,并且知道这个问题是重复的。我发现了几个类似的问题和答案,但我无法弄清这个问题。

我想将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获取变量?


阅读 229

收藏
2020-07-07

共1个答案

小编典典

这听起来可能很奇怪,但是您的代码没有任何问题,但它不能按原样工作。我完全使用了您的代码,但忽略了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()
    }
}
2020-07-07