ØyvindHauge用相同的解决方法击败了我,但正如我已经开始提供更详细的答案一样,我也会添加它。
假设您的两个视图控制器的命名如下:
主/入口:
ViewController (vcA)
次要视图:
ViewControllerB (vcB)
您(vcA) -> (vcB)可以按照示例中的步骤设置序列
// ...// segue ViewController -> ViewControllerBoverride func prepareForSegue(segue: (UIStoryboardSegue!), sender: AnyObject!){ if segue.identifier == "viewNext" { let viewControllerB = segue.destinationViewController as! ViewControllerB viewControllerB.dataPassed = labelOne.text }}在有些麻烦步骤接下来的是,使用该方法,用于SEGUE
传递数据回从
(vcB)to
(vcA)is also added to the source of
(vcA), as an
@IBAction方法(而不是象可能被预期的,添加到源
(vcB)).
// ...// segue ViewControllerB -> ViewController@IBAction func unwindToThisView(sender: UIStoryboardSegue) { if let sourceViewController = sender.sourceViewController as? ViewControllerB { dataRecieved = sourceViewController.dataPassed }}You thereafter connect say, a button in
(vcB)to this unwind action in
(vcA)via the manual
Exitsegue in
(vcB):
Below follows a complete example of passing text from
(vcA)to
(vcB);
(possibly) modifying that text via an
UITextField, finally returning the
(possibly) modified text to
(vcA).
(vcA)source:
import UIKitclass ViewController: UIViewController { var dataRecieved: String? { willSet { labelOne.text = newValue } } @IBOutlet weak var labelOne: UILabel! @IBAction func buttonOne(sender: UIButton) { performSegueWithIdentifier("viewNext", sender: self) } // set default labelOne text override func viewDidLoad() { super.viewDidLoad() labelOne.text = "Default passed data" } // segue ViewController -> ViewControllerB override func prepareForSegue(segue: (UIStoryboardSegue!), sender: AnyObject!) { if segue.identifier == "viewNext" { let viewControllerB = segue.destinationViewController as! ViewControllerB viewControllerB.dataPassed = labelOne.text } } // segue ViewControllerB -> ViewController @IBAction func unwindToThisView(sender: UIStoryboardSegue) { if let sourceViewController = sender.sourceViewController as? ViewControllerB { dataRecieved = sourceViewController.dataPassed } }}(vcB)source (note that the
UITextFieldDelegatedelegate here is only used
for “locally” mutating the value of the
dataPassedproperty, which will be
returned to
(vcA)and assigned to
dataRecievedproperty of the latter)
import UIKitclass ViewControllerB: UIViewController, UITextFieldDelegate { var dataPassed : String? @IBOutlet weak var textField: UITextField! // set default textField text to the data passed from previous view. override func viewDidLoad() { super.viewDidLoad() textField.text = dataPassed // Handle the user input in the text field through delegate callbacks textField.delegate = self } // UITextFieldDelegate func textFieldShouldReturn(textField: UITextField) -> Bool { // User finished typing (hit return): hide the keyboard. textField.resignFirstResponder() return true } func textFieldDidEndEditing(textField: UITextField) { dataPassed = textField.text }}


