How to pass values from a Pop Up View Controller t

2020-05-01 06:33发布

So In my 1stViewController I have this code:

@IBAction func colorDropdown(_ sender: Any) {
    self.popUpColorPicker()
}

func popUpColorPicker() {
    let popOverVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ColorPicker") as! ColorPicker
    self.addChildViewController(popOverVC)
    popOverVC.view.frame = self.view.frame
    self.view.addSubview(popOverVC.view)
    popOverVC.didMove(toParentViewController: self)
}

Which would pop up the 2ndViewController. Upon dismissing the Pop Up 2ndViewController, I'd like to retrieve the values I entered and use it in my 1st View Controller.

3条回答
Animai°情兽
2楼-- · 2020-05-01 06:41

You can achieve this by either using delegate or completion handler.

Just create a delegate to handle your data on dismissing the second VC.

**

OR

**

Write a completion handler closure to get back those values in your first view controller.

查看更多
相关推荐>>
3楼-- · 2020-05-01 06:48

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..!

查看更多
\"骚年 ilove
4楼-- · 2020-05-01 06:54

you can always use unwind to do some stuff upon unwinding

declare a IBAction in your first vc

var color: UIColor!
@IBAction func unwindToCheckout(segue: UIStoryboardSegue) { 
   //do some stuff with color
}

then create exit segue for popout viewcontroller then you can dismiss popout like this

self.performSegueWithIdentifier("unwindToVC1", sender: selectedColor)

then in prepareForSegue

if segue.identifier == "unwindToVC1" {
  (segue.destinationViewController as! FirstViewController).color = sender as! UIColor
}

also you can create delegate to reach fistviewcontroller and do some stuff which is way easier to do

查看更多
登录 后发表回答