【问题标题】:Why am I receiving these errors when trying to pass a variable on a segue in swift?为什么我在尝试快速传递 segue 上的变量时会收到这些错误?
【发布时间】:2015-03-31 20:53:01
【问题描述】:

我正在尝试以here 给出的答案为基础。我想要做的很简单——我想要一个可以输入文本的文本字段。您按下 go 按钮,它会将您带到一个新视图,并将该页面上标签上的文本替换为用户在框中输入的任何内容。这是我在第一页使用的代码。

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'

谢谢。

【问题讨论】:

    标签: xcode swift views segue


    【解决方案1】:

    您应该在声明中将字典设置为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
                }
            }
        }
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-24
        • 2011-11-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-13
        相关资源
        最近更新 更多