2015-06-25 102 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) 
    }  
} 
相關問題