时间:2015-06-25 01:14:28

标签: ios swift segue

我试图在视图控制器之间传递一个字符串。当我通过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,但是视图中的文本字段具有上一个视图中的字符串,当我按下提交按钮并执行我的submitForm函数时,字段会传递所需的字符串。我暂时通过将其存储在NSUserDefaults中来解决这个问题,但我仍然对此感到好奇。

1 个答案:

答案 0 :(得分: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)
    }    
}