Xie Xie - 3 days ago 5
Swift Question

Pass data backward from detailViewController to masterViewController

I am trying to pass data back from the second viewController.
I can do that without NavigationController. But now I need to use NavigationController. Then my code does work as before. The data wont pass.
Here is the simple code:
In first viewController

class ViewController: UIViewController, backfromSecond {

@IBOutlet weak var text: UILabel!

var string : String?

override func viewDidLoad() {
super.viewDidLoad()
self.string = "Start here"
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
self.text.text = self.string
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destinationViewController = segue.destination as? secondViewController{
destinationViewController.delegate = self
}
}

func back(text: String) {
self.string = text
print(text)
}
}


And Second viewController:

protocol backfromSecond {
func back(text: String)
}
class secondViewController: UIViewController {
var string : String = "nothing here"
var delegate : backfromSecond?
override func viewDidLoad() {
super.viewDidLoad()
delegate?.back(text: string)
// Do any additional setup after loading the view.
}
}


What is wrong here?

Answer

Suppose A & B are two controllers and you first navigated from A to B with some data. And now you want to POP from B to A with some data.

Unwind Segues is the best and recommended way to do this. Here are the steps.

  1. Open A.m
  2. define following method

    @IBAction func unwindSegueFromBtoA(segue: UIStoryNoardSegue) {

    }

  3. open storyboard

  4. Select B ViewController and click on ViewController outlet. press control key and drag to 'Exit' outlet and leave mouse here. In below image, selected icon is ViewController outlet and the last one with Exit sign is Exit Outlet.

  5. You will see 'unwindSegueFromBtoA' method in a popup . Select this method .

  6. Now you will see a segue in your view controler hierarchy in left side. You will see your created segue near StoryBoard Entry Piont in following Image.

You View Hierarchy

  1. Select this and set an identifier to it. (suggest to set the same name as method - unwindSegueFromBtoA)

  2. Open B.m . Now, wherever you want to pop to A. use

    self.performSegueWithIdentifier("unwindSegueFromBtoA", sender: dataToSend)

  3. Now when you will pop to 'A', 'unwindSegueFromBtoA' method will be called. In unwindSegueFromBtoA of 'A' you can access any object of 'B'.

  4. That's it..!

Comments