为什么我尝试在 swift 中的 segue 上传递变量时收到这些错误?

Why am I receiving these errors when trying to pass a variable on a segue in swift?

我正在尝试根据 给出的答案进行构建。我想要做的非常简单——我想要一个文本字段,您可以在其中输入文本。您按下“开始”按钮,它会将您带到一个新视图,并用用户在框中输入的任何内容替换该页面上标签上的文本。这是我在第一页上使用的代码。

import UIKit

class ViewController: UIViewController {

    @IBOutlet var entry: UITextField!

    let dictionary = entry.text // Line 7 ERROR


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "viewTwo"
        {
            if let destinationVC = segue.destinationViewController as? viewTwo{
                destinationVC.dictionary = self.dictionary // Line 24 ERROR
            }
        }
    }

    @IBAction func goToViewTwo(sender: AnyObject) {
        performSegueWithIdentifier("viewTwo", sender: self)
    }

}

我只包含第一个视图中的代码,因为我知道第二个视图中的代码可以正常工作。

在我尝试使用文本字段之前我没有遇到错误 - 之前我只是有一个预先选择的文本来传输它工作。之前,我没有使用 let dictionary = entry.text,而是使用了 let dictionary = "foo",而且它起作用了。

所以我的问题是完全一样的,但有一个文本字段而不是预先选择的文本 - 我真正想知道的是为什么我的代码以前不起作用。

我得到的错误在第 7 行(我已经标记了上面有错误的行)- 'ViewController.Type' does not have member names 'entry' 并且在第 24 行也有错误,但我怀疑这与此错误有关并且如果此错误也已修复,将被修复。以防万一,第 24 行的错误是:'ViewController.Type' does not have member names 'dictionary'

谢谢。

字典不是常量,所以声明为lazy var,而不是let:

lazy var dictionary: String {
     return entry.text
}()

您应该在声明中将字典设置为 var dictionary = ""。您在这里使用 var 而不是 let,以便稍后可以更改 dictionary 的值。

然后在 @IBAction func goToViewTwo(sender: AnyObject){} 方法中,设置 self.dictionary = entry.text

 @IBAction func goToViewTwo(sender: AnyObject) {
        dictionary = entry.text
        performSegueWithIdentifier("viewTwo", sender: self)
    }

或者,您可以在prepareForSegue()方法中执行以下操作。 这样,您不需要声明 dictionary 来保存 UITextField 的文本值,您只需将 entry 中的文本值传递给第二个视图控制器的 dictionary 变量即可。

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "viewTwo"
        {
            if let destinationVC = segue.destinationViewController as? viewTwo{
                destinationVC.dictionary = self.entry.text
            }
        }
    }