2015-03-31 22 views
0

我想建立在我被给予的答案here。我想要的是非常简单的 - 我想要一个可以输入文本的文本字段。您按下go按钮,它会将您带到一个新视图,并用该用户在框中输入的内容替换该页面上标签上的文本。这是我在第一页上使用的代码。为什么在尝试在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'

谢谢。

回答

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 
      } 
     } 
    } 
0

字典是不是恒定的,所以声明它为lazy var,不let

lazy var dictionary: String { 
    return entry.text 
}() 
相关问题