2015-06-25 51 views
-2

我试图在视图控制器之间传递一个字符串。当我通过prepareForSegue将一个字符串传递给UIButton的文本时,它可以工作,但是当我尝试将它传递给一个声明为“id:String!”的字符串时,它仍然为零。我认为这是因为当我打电话给prepareForSegue时变量还没有初始化,但我不知道如何解决它。在视图控制器之间传递字符串

对不起,这里是我的代码:

class signUpViewController: UIViewController { 
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { 
    if segue.identifier == "toSignUp" { 
     if let destinationVC = segue.destinationViewController as? signUpViewController { 
      destinationVC.firstNameField.text = self.firstName 
      destinationVC.lastNameField.text = self.lastName 
      destinationVC.emailField.text = self.email 
      destinationVC.facebookID = self.facebookID 
     } 
    } 
} 

class signUpViewController: UIViewController { 
    @IBOutlet weak var firstNameField: UITextField! 
    @IBOutlet weak var lastNameField: UITextField! 
    @IBOutlet weak var emailField: UITextField! 
    var facebookID: String! 
    viewDidLoad() { 
     print(facebookID) 
    }  
} 

还是没能解决这个问题。我在viewDidLoad中打印了firstNameField.text,它也是nil,但视图中的文本字段具有前一视图中的字符串,当我按下submit按钮并执行submitForm函数时,字段会传递所需的字符串。我暂时通过将它存储在NSUserDefaults中来解决这个问题,但我仍然对此感到好奇。

+0

请出示相关的代码。 – ndmeiri

+1

如果您的特定代码不能按预期工作,请发布该代码。 –

+0

对不起,我添加了代码。 – user19933

回答

0

你是对你的变量尚未初始化,试试这个:

class signUpViewController: UIViewController { 
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { 
    if segue.identifier == "toSignUp" { 
     if let destinationVC = segue.destinationViewController as? signUpViewController { 
      //pass the values to the strings that are initialized with the object 
      destinationVC._firstNameField = self.firstName 
      destinationVC._lastNameField = self.lastName 
      destinationVC._emailField = self.email 
      destinationVC.facebookID = self.facebookID 
     } 
    } 
} 

class signUpViewController: UIViewController { 
    @IBOutlet weak var firstNameField: UITextField! 
    @IBOutlet weak var lastNameField: UITextField! 
    @IBOutlet weak var emailField: UITextField! 
    //Create and initialize strings 
    var _sfirstNameField = String() 
    var _slastNameField = String() 
    var _semailField = String() 
    var facebookID = String() 
    viewDidLoad() { 
     //pass the values from the strings to the now initialized UITextField 
     firstNameField.text = _firstNameField 
     lastNameField.text = _lastNameField 
     emailField.text = _emailField 
     print(facebookID) 
    }  
} 
相关问题